我在C中制作了一个程序,用尽可能少的账单来计算要提取的资金。一切都按预期工作,但出于某种原因,返还的美元钞票数量几乎总是一个。例如,如果我输入我要撤回549,它会给5美元钞票,两个二十,一个五,但是三美元而不是四美元,总计548。如果我想要320,它会给 - 1美元回来。我不确定该程序有什么问题 - 我检查了数学和所有内容,并在不同的编译器上进行了尝试。任何帮助将不胜感激。
#include <stdio.h>
int main()
{
int amountToWithdraw = 0;
int hundredsWithdrawn = 0;
int fiftysWithdrawn = 0;
int twentysWithdrawn = 0;;
int tensWithdrawn= 0;
int fivesWithdrawn= 0;
int onesWithdrawn= 0;
printf ("Please enter the amount of money you wish to withdraw:");
scanf ("%d", &amountToWithdraw);
hundredsWithdrawn = amountToWithdraw / 100;
amountToWithdraw = amountToWithdraw % 100;
fiftysWithdrawn = (amountToWithdraw - hundredsWithdrawn) / 50;
amountToWithdraw = amountToWithdraw % 50;
twentysWithdrawn = (amountToWithdraw - fiftysWithdrawn) / 20;
amountToWithdraw = amountToWithdraw % 20;
tensWithdrawn = (amountToWithdraw - twentysWithdrawn) / 10;
amountToWithdraw = amountToWithdraw % 10;
fivesWithdrawn = (amountToWithdraw - tensWithdrawn) / 5;
amountToWithdraw = amountToWithdraw % 5;
onesWithdrawn = (amountToWithdraw - fivesWithdrawn) / 1;
printf ("You received %d hundred(s)", hundredsWithdrawn);
printf ("You received %d fifty(s)", fiftysWithdrawn);
printf ("You received %d twenty(s)",twentysWithdrawn);
printf ("You received %d ten(s)", tensWithdrawn);
printf ("You received %d five(s)", fivesWithdrawn);
printf ("You received %d one(s)", onesWithdrawn);
return 0;
}
答案 0 :(得分:1)
我不喜欢使用StackOverflow作为“修复我的代码”服务,甚至没有阅读代码开始......
但我很想知道有多少错误,并在此过程中修复了它。
这应该合理得当:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int money = 0;
int hundreds = 0;
int fiftys = 0;
int twentys = 0;
int tens = 0;
int fives = 0;
int ones = 0;
printf("Please enter the amount of money you wish to withdraw:");
scanf("%d", &money);
hundreds = money / 100;
money %= 100;
fiftys = money / 50;
money %= 50;
twentys = money / 20;
money %= 20;
tens = money / 10;
money %= 10;
fives = money / 5;
money %= 5;
ones = money / 1;
printf("You received %d hundred(s)\n", hundreds);
printf("You received %d fifty(s)\n", fiftys);
printf("You received %d twenty(s)\n",twentys);
printf("You received %d ten(s)\n", tens);
printf("You received %d five(s)\n", fives);
printf("You received %d one(s)\n", ones);
return 0;
}
scanf()
printf
答案 1 :(得分:1)
您的程序逻辑错误。而不是:
fiftysWithdrawn = (amountToWithdraw - hundredsWithdrawn) / 50;
它应该是:
fiftysWithdrawn = amountToWithdraw / 50;
和所有其他类似的线类似。
您已经丢弃了数百个(通过执行amountToWithdraw = amountToWithdraw % 100;
),因此您不需要将它们计入剩余的计算中。
549
的“关闭一个”错误是因为在最后一步中onesWithdrawn = (4 - 1) / 1;
提供3
,实际上它应该是4
。 1
来自fivesWithdrawn
的虚假使用。因此,我希望您找到以5,6,7,8,9
结尾的任何金额的off-by-one错误,而不是其他金额。
其他音符不会显示错误,因为误差量小于您所划分的误差,例如再次使用549
,您可以(49 - 5) / 20
获取二十位数,但这与正确的版本49 / 20
给出相同的答案。
顺便说一下,您可能希望使用%=
运算符来使您的代码可读;它的工作方式是A %= B
表示A = A % B
。并在printf的末尾使用\n
。