I'm working on the "cash" problem from CS50x pset1, and I'm having trouble finding the problem with my code. Most of the answers are correct, but when I input "0.56", the return value is "5" which is not correct. Thanks for the help!

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

int main (void) {
    float change;
    do {
       change = get_float ("Change owed: ");
    while (change < 0);

    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    while (change >= 0.25)
        change = change - 0.25;

    while (change >= 0.10)
        change = change - 0.10;

    while (change >= 0.05)
        change = change - 0.05;

    while (change > 0)
        change = change - 0.01;

    printf ("%i", a + b + c + d);
    printf ("\n");

Looks like a rounding error.

To solve this, you might take another look at the second hint, at the bottom of the exercise:

Do beware the inherent imprecision of floating-point values. For instance, 0.1 cannot be represented exactly as a float. ... And so, before making change, 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!

You will find more details about how to solve this if you have a look at the bottom of the exercise.

And to quote Cliff B:

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

You must log in to answer this question.

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