I am using while loops (every time change is greater than quarter, have coins used added by one and subtract the amount of change by the amount just taken away). All of my values are converted to ints, but I constantly get a print value of 0. I have used python and these programs are very easy to make but this is frustrating me.
A correct way is to avoid dealing with
floats because they're not precise and to deal with
ints 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
- calculate the number of coins and output it followed by a newline character.
ints 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
floats 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
ints, 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 shouldn't be reading the float like that
you're not rounding the amount you get from the user.
- you have logical errors in your code.
- you shouldn't be printing the value of
How to fix these?
you should rather be reading the
floateither like this
change = GetInt(); // from the cs50 library
round()function (declared in
math.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.,
}) 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 as
condition 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
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 of
Zamyla in the walkthrough suggests using the
float roundf(round x) helped me.
You can see how to use it by typing "man round" into your terminal. "man round" will bring up the manual (man) page for
Round is included in the math.h library so don't forget to add that to your program if you use this function.
It will get rid of that pesky truncating issue.