gpt4 book ai didi

c - C 语言的简单硬币找零程序

转载 作者:行者123 更新时间:2023-11-30 20:31:12 24 4
gpt4 key购买 nike

所以我必须制作一个硬币找零程序,用户输入价格以及他们支付的金额,输出必须是他们的硬币、硬币、镍币、便士的零钱。由于某种原因,我的程序不会给出正确的输出。如果我输入价格为 40 美分,输入支付的金额为 50 美分,它会显示所需找零是 10 美分,但 2 毛钱,所以它给了我额外的一毛钱。如果有人能帮助我,我将不胜感激。

int main()
{

int numberOfQuarters =0;
int numberOfDimes =0;
int numberOfNickels =0;
int numberOfPennies =0;

int price;
int paid;
int change;



printf("Please enter the price of your item in cents: ");
scanf("%d", &price);

printf("Please enter the amount of money you gave in cents: ");
scanf("%d", &paid);

change = (paid - price);
printf("Change required: %d", change);

while(change >= 25)
{
numberOfQuarters++;
if(numberOfQuarters >0 )
{
change = (change - (numberOfQuarters * 25));
}
printf("\nNumber of Quarters:%d", numberOfQuarters);
}

while((change >= 10) && (change < 25))
{
numberOfDimes++;
if(numberOfDimes > 1)
{
change = (change - (numberOfDimes * 10));
}
}
while((change >= 5) && (change < 10))
{
numberOfNickels++;
if(numberOfNickels >0)
{
change = (change - (numberOfNickels * 5));
}
}

printf("\nThe number of quarters: %d", numberOfQuarters);
printf("\nThe number of dimes: %d", numberOfDimes);
printf("\nThe number of nickels: %d", numberOfNickels);
printf("\nThe number of pennies: %d", change);

}

最佳答案

一个简单的逻辑错误。

if(numberOfDimes > 1) 更改为 if(numberOfDimes > 0)

更好的是,您不需要 block 内的 if 语句。如果程序到达 while 循环内部,则 if 语句始终为 true。

关于c - C 语言的简单硬币找零程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52278930/

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