Small bug in my short C code. Why?

后端 未结 3 1111
不思量自难忘°
不思量自难忘° 2021-01-23 12:11

I can\'t figure out why this works for 90% of the inputs, but not the others. It is meant to tell you how many coins you would get back in change. Most test amounts work fine,

3条回答
  •  余生分开走
    2021-01-23 12:30

    The other answers have it mostly covered: you should be working with fixed point here, not floating point. Be careful to round properly when going from the floating point input to your fixed point representation, though. Here is a short version I hacked up, which should work for all positive inputs:

    #include 
    #include 
    int main(int argc, char ** argv)
    {
        float change = atof(argv[1]);
        int work = (int)(100*change+0.5);
        int quarters, dimes, nickels, pennies;
        quarters = work/25; work %= 25;
        dimes    = work/10; work %= 10;
        nickels  = work/5;  work %=  5;
        pennies  = work;
        printf("%.2f dollars = %d quarters, %d dimes, %d nickels and %d pennies: %d coins total\n",
        change, quarters, dimes, nickels, pennies, quarters+dimes+nickels+pennies);
        return 0;
     }
    

    For example:

    ./change 4.20
    4.20 dollars = 16 quarters, 2 dimes, 0 nickels and 0 pennies: 18 coins total
    

提交回复
热议问题