简体   繁体   中英

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. 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.

    #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.

See Joachim comment: c least amount of coins for amount entered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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