i´ve been trying to figure out what is wrong with my code for the pset1 cash or greedy program, i know about float imprecision but when i print the last value for "ch" it prints .01000, thus meaning that it should actually run one more time adding the missing penny, but i must be missing something... Help!

Here's my code:

#include <stdio.h>
#include <cs50.h>

int main(void)
    int quarter = 0, dime = 0, nickel = 0, penny = 0, coin = 0;

    float ch = get_float("Change Owed: $");

    for (quarter = 0; ch >= .25; coin++)
        ch = ch - .25;
    for (dime = 0; ch >= .10; coin++)
        ch = ch - .10;
    for (nickel = 0; ch >= .05; coin++)
        ch = ch - .05;
    for (penny = 0; ch >= .01; coin++)
        ch = ch - .01;
 printf("%i\n", coin);

Perhaps you don't understand float imprecision fully enough. If you were to print the value of ch with more digits of precision, you would see what's happening. Try using the following:

 printf("%0.32f\n", ch);

This will show a more accurate value of what is in ch, rather than a rounded off value generated by the default precision resulting from the printf statement.

printf defaults to printing floats to about 8 digits of precision. It will round the last digit, the 8th digit, based on what follows. The actual value is stored to about 29 digits of decimal precision. So, for example, 0.009999999999999999 will be printed as 0.01 using the default print precision.

While in the real world, the algorithm above seems like it would work, it completely misses the point of the exercise. The problem with floating point imprecision must be dealt with before executing all of the calculations. Imagine if a bank made this kind of error, just off by a "fraction of a penny." Now, magnify that by thousands of customers and millions of transactions. The accountants would go insane!!! ;-)

Someone at a bank once took advantage of this by programming a tiny fraction of a penny's worth of interest from all the interest calculations each month at a major bank. By transferring these "rounding errors" of about 0.001 cents or less at a time to a separate account, they were able to divert thousands of dollars! Well, until they were caught by an audit. I think there was even a fictional movie made, based on this.

I recommend going back and reviewing the lectures and the walkthrough videos.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)


first you need to figure out some ideas like where and how to use for loop, float, boolean, round and other ideas. what i can tell you just go around google search some of and try again to listen carefull Walkthroughs. you will what you need

You must log in to answer this question.

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