简体   繁体   English

至少要输入的硬币数量

[英]c least amount of coins for amount entered

So I am new and trying to write a program to get input for an amount of money $XX.XX then display the least amount of coins to make that amount. 因此,我是新手,尝试编写一个程序以获取金额为$ XX.XX的输入,然后显示最少数量的硬币即可赚取该金额。 I have made a program that works but it is often off by a penny when doing some calculations for example when 13.49 and I can't figure out why. 我制作了一个程序,但是在进行一些计算时(例如在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]));
            }
        }
    }

It's off because of cumulative rounding errors inside calculations. 由于计算中存在累积舍入误差,因此无法使用。

You can use double for more precision. 您可以使用double来提高精度。

See Joachim comment: c least amount of coins for amount entered 参见Joachim评论: 输入的数量最少为硬币数量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM