因此,我必须制作一个“硬币找零制作器”程序,用户在其中输入价格和支付的金额,而输出则必须是他们的四分之一硬币,硬币,小费和便士硬币。由于某种原因,我的程序无法提供正确的输出。如果我输入价格为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);
}
答案 0 :(得分:0)
一个简单的逻辑错误。
将if(numberOfDimes > 1)
更改为if(numberOfDimes > 0)
。
更好的是,您不需要块内的if
语句。如果程序到达while循环内部,则if语句将始终为true。
答案 1 :(得分:0)
while(change >= 25)
{
numberOfQuarters++;
if(numberOfQuarters >0 )
{
change = (change - (numberOfQuarters * 25));
}
printf("\nNumber of Quarters:%d", numberOfQuarters);
}
此结构是错误的,因为在此代码中,第二季度的价值将增加两倍,而第三季度的价值将增加第三倍。您不需要乘以numberOfQuarters
,也不需要检查numberOfQuarters
是否为正,因为从零开始递增(如果不发生溢出),它必须为正。
此部分应如下所示:
while(change >= 25)
{
numberOfQuarters++; /* add one more quarter */
change = change - 25; /* subtract the value of one quarter because one is added */
printf("\nNumber of Quarters:%d", numberOfQuarters);
}
角钱和镍价的计算也应采用这种方式。
使用两个一角硬币的原因是,由于某种原因,您倾向于在只有一个一角硬币的情况下不降低一角硬币的值。
答案 2 :(得分:0)
因此,既然已经解决了主要问题,那么我不妨提出另一种实现方式:
#include <stdio.h>
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);
numberOfQuarters += change / 25;
change %= 25;
numberOfDimes += change / 10;
change %= 10;
numberOfNickels += change / 5;
change %= 5;
numberOfPennies = change;
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\n", change);
}
这样,您可以避免出现任何循环,而只需使用除法和提醒即可。