0

I'm encountering some problem with my code with regards to pset1 Greedy! For some odd reason my code can't seem to compute pennies? So whenever i put in any values that has a 0.01 it won't calculate it in.

Is there anything fundamentally wrong with my code? I tried changing the condition for the part that calculates the pennies but can't seem to get it right...

Any help would be greatly appreciated!!

if (change > 0.0)
{
    // Checking how many quarters to return in change
    for (float i = change; i >= 0.25; i = i - 0.25)
    {
        coins++;
        change = change - 0.25;
    }

    // Checking how many dimes to return in change
    for (float i = change; i >= 0.10; i = i - 0.10)
    {
        coins++;
        change = change - 0.10;
    }

    // Checking how many nickels to return in change
    for (float i = change; i >= 0.05; i = i - 0.05)
    {
        coins++;
        change = change - 0.05;
    }

    // Checking how many pennies to return in change
    for (float i = change; i >= 0.01; i = i - 0.01)
    {
        coins++;
        change = change - 0.01;
    }

    // letting the user know how many coins is needed in change
    printf("%d\n", coins);

1 Answer 1

4

One of the goals of this pset is to teach some of the issues with computer storage of numbers. One of the biggest issues is that when a number is stored as a float, it may not be stored exactly as what you expect. For instance, 4.2 may be stored as 4.1999999978 or something similar. Another number, say 3.31 may be stored as 3.310000000002. (These are, of course, just hypothetical examples. Your processor may vary.)

Now with your code, what happens when you get down to the end? On that very last cycle, you think you have 1 cent left, but the float is storing 0.009999978. Since that is less than 0.01, the loop exits and you missed by a penny. Try inserting printf("Change = %f \n", change); just after change = change - 0.01; in the last loop and see what your change value is decrementing to before the last exit.

That's why the pset talks about converting to an integer before figuring out the number of coins. Figuring out the best way to do that conversion is another prime reason for the pset. The pset document on the web is a great roadmap. You might benefit from going back through it again.

So, that should get you going. If you're happy with this, please mark your question as answered. Let's keep up on forum housekeeping. ;-)

1
  • Awesome! Thanks so much for your help! :)
    – Joel Tan
    May 11, 2015 at 7:33

You must log in to answer this question.

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