A correct way is to avoid dealing with float
s because they're not precise and to deal with int
s instead. To do that you should
- convert the amount you receive from the user in dollars (the
float
) to be in cents. - round the amount (in cents) to the nearest integer and store it in an
int
variable. - calculate the number of coins and output it followed by a newline character.
Casting float
s to int
s truncates the digits after the decimal point. So if you're casting a value between 0.0 and 1.0 to an int
, it will be stored as 0. Besides, because float
s are not precise, even the whole numbers like 1.0 or 2.0 can be stored as 0.9999999 and 1.9999999 respectively. When you then cast these to int
s, they'll be stored as 0 and 1 respectively (not 1 and 2 as they should).
Update: after reviewing your code, I could identify the following bugs
- you're not rounding the amount you get from the user.
you shouldn't be reading the float like that
scanf("%.2f\n", &change);
- you have logical errors in your code.
you're not rounding the amount you get from the user.
- you shouldn't be printing the value of
change
.you have logical errors in your code.
you shouldn't be printing the value of
change
.
How to fix these?
you should rather be reading the
float
either like thischange = GetInt(); // from the cs50 library
or this
scanf("%f", &change);
use the
round()
function (declared inmath.h
) to round the amount that you receive from the user.given the following piece of code
while (condition) printf("hello from inside the loop!\n"); printf("hello from outside the loop!\n");
As you might have noticed, when you don't use curly braces (i.e.,
{
and}
) to enclose the body of the loop, only the first statement right after the loop is the one that's inside that body of this loop (and that's gonna keep executing as long ascondition is true
). All the following statements are out of the body of the loop and are executed anyway. You're having many similar problems like this in your code.Also, the loops that calculate the number of dimes and nickles shouldn't be nested inside the loop that calculates the number of quarters because if initially
change
is <quarter
, the body of this loop is never executed. And thus, we won't calculate the number of coins correctly (and that's the one that might be causing your program to print zeros).you should remove all
printf()
calls that print the value ofchange
.