c输入金额的最少金额

时间:2016-01-23 20:13:28

标签: c

所以我是新手并试图编写一个程序来获取金额$ XX.XX的输入然后显示最少量的硬币来赚取金额。我已经制作了一个有效的程序,但在进行一些计算时经常是一分钱,例如在13.49时,我无法找出原因。

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

    int main()
    {
        int StayOn = 1;
        while (StayOn == 1)
        {
            int x = 0;
            float MoneyStart = 0, RemainingMoney = 0;
            char cName[6][8] = {"Toonie", "Loonie", "Quarter", "Dime", "Nickel", "Penny"};
            float cValue[6] = {2.00, 1.00, 0.25, 0.10, 0.05, 0.01};
            int cCount[6] = {0, 0, 0, 0, 0, 0};

            printf("Please Enter Amount: $");
            scanf("%f", &MoneyStart);
            getchar();

            RemainingMoney = MoneyStart;

            for (x = 0; x < 6; x++)
            {
                cCount[x] = (RemainingMoney / cValue[x]);
                RemainingMoney = fmod(RemainingMoney, cValue[x]);
                printf("%8s  - %3i = $%.2f\n", cName[x], cCount[x], (cValue[x]*cCount[x]));
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

由于计算中的累积舍入错误,它已关闭。

您可以使用double来提高精确度。

请参阅Joachim评论:c least amount of coins for amount entered