我是C的新手,很了解python但是我正在努力解决一些基本问题,这真的令人沮丧,因为我似乎无法确定我的代码不会让while循环中断,直到它达到数字为止我假设与缓冲区有关,然后它只是命中我程序中的每个条件,任何人都有一些见解?
这是我插入10时得到的输出:
Welcome to the Soda Vending Machine
All sodas cost $1.50 each
This machine accepts the following coins:
nickel = 5, dime = 10, quarter = 25, half-dollar = 50, dollar = 100
Please use the numeric value corresponding to each coin
10
Amount depositied so far: $ 32767
Amount depositied so far: $ 32777
Amount depositied so far: $ 32777
Amount depositied so far: $ 32777
Amount depositied so far: $ 32777
Invalid Coin
Dispensing soda ...
Your change is: Half dollar quarter dime nickel
int main(void)
int coin;
int totalcoin;
char *change = "Your change is:" ;
printf("Welcome to the Soda Vending Machine\n===================================\nAll sodas cost $1.50 each\nThis machine accepts the following coins:\nnickel = 5, dime = 10, quarter = 25, half-dollar = 50, dollar = 100\nPlease use the numeric value corresponding to each coin\n");
while (totalcoin < 150)
printf("Deposit a Coin: ");
scanf("%d", &coin);
if ( coin == 5)
totalcoin = totalcoin + 5;
printf("Amount depositied so far: $ %d\n", totalcoin);
if (coin == 10)
totalcoin = totalcoin + 10;
printf("Amount depositied so far: $ %d\n", totalcoin);
if (coin == 25)
totalcoin = totalcoin + 25;
printf("Amount depositied so far: $ %d\n", totalcoin);
if (coin == 50)
totalcoin = totalcoin + 50;
printf("Amount depositied so far: $ %d\n", totalcoin);
if (coin == 100)
totalcoin = totalcoin + 100;
printf("Amount depositied so far: $ %d\n", totalcoin);
if (coin != 5 || coin !=10 || coin !=25 || coin !=50 || coin !=100)
printf("Invalid Coin\n");
printf("Dispensing soda ...\n");
printf("Your change is: ");
if (totalcoin > 50)
totalcoin -= 50;
printf("Half dollar");
if (totalcoin >= 25)
totalcoin -= 25;
printf(" quarter");
if (totalcoin >= 10)
totalcoin -= 10;
printf(" dime");
if (totalcoin >= 5)
totalcoin -= 5;
printf(" nickel");
答案 0 :(得分:3)
if ( coin == 5)
totalcoin = totalcoin + 5;
printf("Amount depositied so far: $ %d\n", totalcoin);
缩进没有显示它真正的作用。它实际上相当于:
if ( coin == 5)
{
totalcoin = totalcoin + 5;
}
printf("Amount depositied so far: $ %d\n", totalcoin);
这不是你的意思,你应该使用一个块:
if ( coin == 5)
{
totalcoin = totalcoin + 5;
printf("Amount depositied so far: $ %d\n", totalcoin);
}
作为最佳做法,有些人会选择在if
,for
,while
等之后始终使用块,即使块中只有一个语句也是如此。它不易出错,特别是当你需要添加更多语句时。