我用C语言编写了一个程序,该程序以尽可能少的票据金额来计算要提取的钱。一切正常,但由于某种原因,退还的美元钞票几乎总是相差一。例如,如果我键入要提取549,它会给500美元的钞票,两个二十,一个五,三个美元,而不是四个,总共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;
}

最佳答案

您的程序逻辑是错误的。代替:

fiftysWithdrawn = (amountToWithdraw - hundredsWithdrawn) / 50;


它应该是:

fiftysWithdrawn = amountToWithdraw / 50;


对于所有其他此类行也是如此。

您已经丢弃了数百个(通过执行amountToWithdraw = amountToWithdraw % 100;),因此无需将它们计入其余的计算中。



549出现“偏离一位”错误的原因是,在最后一步中,您实际上是onesWithdrawn = (4 - 1) / 1;给出了3时给出了41来自fivesWithdrawn的虚假使用。因此,我希望您发现以5,6,7,8,9结尾的任何金额而不是其他金额的一字不漏错误。

该错误不会针对其他注释显示,因为错误的数量小于您所除的错误数量,例如再次使用549,您可以执行(49 - 5) / 20来获取二十位数字,但这给出的答案与正确版本49 / 20相同。

顺便说一句,您可能想使用%=运算符使代码可读;它的工作方式是A %= B表示A = A % B。并在printf的末尾使用\n

关于c - 提款计算器始终在给定的一美元钞票金额中关闭,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27975589/

10-11 19:07