0

I don't know what is wrong with my code. It works with a 60 cent input for example, it gives me 3 coins, and I know how many of each because I can "see" the code running by using printf to print out the values. But if my input is 35 cents it will pass right through the 10 cent part of the code.

The thing is I know the 10 cents part works, because it goes through there if my input is 60 cents, it goes twice by 25 cents, I have 10 cents left so it goes through the 10 cent part of the code and that's it.

Here is the 10 cents part:

if (change >= 0.10) 
{
    do
    {
        count++;
        change = change - 0.10;
        printf("B%d\n", count);
        printf("%0.2f\n", change);  
    }
    while (change >= 0.10);
}
1

If you increase the precision of your printf format strings from 2 decimal places to 20 decimal places, you will see that using floating point arithmetic, 0.35 - 0.25 is very slightly less than 0.10. Here's a runnable demonstration on ideone.

This is what the problem set 1 specification is warning about when it says:

Incidentally, do beware the inherent imprecision of floating-point values. For instance, 0.01 cannot be represented exactly as a float. Try printing its value to, say, 50 decimal places, with code like the below:

float f = 0.01;
printf("%.50f\n", f);

Before doing any math, then, you’ll probably want to convert the user’s input entirely to cents (i.e., from a float to an int) to avoid tiny errors that might otherwise add up! Of course, don’t just cast the user’s input from a float to an int! After all, how many cents does one dollar equal? And be careful to round and not truncate your pennies!

For more details about floating point arithmetic, here are some related questions:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .