gpt4 book ai didi

c - 编写 Vending 程序,while 语句不会中断?

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:06 25 4
gpt4 key购买 nike

我是 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");

最佳答案

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);

这不是你的意思,你应该使用 block :

if ( coin == 5)
{
totalcoin = totalcoin + 5;
printf("Amount depositied so far: $ %d\n", totalcoin);
}

作为最佳实践,有些人选择始终在 ifforwhile 等之后使用 block ,即使只有 block 中的一个语句。它不太容易出错,尤其是当您需要向其中添加更多语句时。

关于c - 编写 Vending 程序,while 语句不会中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com