【发布时间】:2017-04-04 22:04:22
【问题描述】:
我正在尝试模拟自动售货机。我的程序将命令行输入的金额作为价格,然后继续提示,直到程序中止。我试图通过一个while-do循环来实现这一点,我现在知道这一定是错误的。我需要程序继续提示输入硬币,即使他们已经插入了写入数量的硬币。
代码应如何编译的示例如下: $ - 表示命令行
$ pop 225
Price must be from 10 to 100 cents
$ pop 86
Price must be a multiple of 5.
$ pop 50
Welcome to my Vending Machine!
Pop is 50 cents. Please insert nickels, dimes, or quarters.
Enter coin [NDQ]:d
You have inserted a dime
Please insert 40 more cents.
Enter coin [NDQ]:d
You have inserted a dime
Please insert 30 more cents.
Enter coin [NDQ]:d
You have inserted a dime
Please insert 20 more cents.
Enter coin [NDQ]:d
You have inserted a dime
Please insert 10 more cents.
Enter coin [NDQ]:d
You have inserted a dime
Pop is dispensed. Thank you for you business! Please come again.
Enter coin [NDQ]
看看最后它是如何回到能够输入硬币的,直到选择 E 退出。但是,我正在尝试执行此操作,我的代码当前在初始输入 N、D 或 Q 时陷入无限循环。不胜感激任何帮助或指导。谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define NI 5
#define DI 10
#define QU 25
bool isValid(int num) {
return (num >= 10 && num <= 100 );
}
bool isMultiple(int num) {
return (num % 5 == 0);
}
int
main (int argc, char *argv[])
{ for (int i = 1; i != argc; ++i) {
int price = atoi(argv[i]);
if (!isValid(price)) {
printf("Price muse be from 10 cents to 100 cents.\n");
break;
} else if (!isMultiple(price)) {
printf("Price must be a multiple of 5.\n");
break;
} else {
printf(" Welcome to my Vending Machine!\n");
printf("Pop is %d cents. Please enter nickels, dimes, or quarters\n", price);
char coin;
do
{
printf(" PLease enter a coin [NDQR]\n");
scanf (" %c", &coin);
int cents = 0;
while (cents <= price) {
if (coin == 'N'|| coin == 'n') {
cents = cents + NI;
printf(" You have inserted 5 cents\n");
}
else if (coin == 'd' || coin == 'D') {
cents = cents + DI;
printf("You have inserted 10 cents\n");
}
else if (coin == 'Q' || coin == 'q') {
cents = cents + QU;
printf("You have entered 25 cents\n");
} else {
printf("Unknown coin. Rejected.\n");
}
int balance = price - cents;
printf("You have entered a total of %d cents\n", cents);
if (balance > 0) {
printf("You must enter %d more cents\n", balance);
} else {
int change = cents - price;
int dimes = change/10;
int remainder = change % 10;
int nickles = remainder/5;
int remainder2= nickles % 5;
printf("Change returned. %d nickles and %d dimes",nickles, dimes);
}
}
} while (coin != 'E' && coin != 'e');
printf("DONE!\n");
return 0;
}
}
}
【问题讨论】:
-
coin != 'E' || coin != 'e'始终为真。 -
我怎样才能做到这一点,以便它循环直到输入 E?
-
在倒数第二个
printf中,拼写错误:将“nickles”更改为“nickels”。
标签: c debugging while-loop do-while