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

int main(void)
{
    float change, quarter, dime, nickel, penny;
    int coins;
    do {
     change = get_float("Change: ");
    } while (change < 0);

    quarter = 0.25;
    dime = 0.10;
    nickel = 0.05;
    penny = 0.01;
    coins = 0;



    while (change != 0)
    {
        if((change-quarter) >= 0)
        {
            change = change - quarter;
            coins += 1;
        }
        else if ((change - dime) >= 0)
        {
            change = change - dime;
            coins += 1;
        }
        else if ((change - nickel) >= 0)
        {
            change = change - nickel;
            coins += 1;
        }
        else if ((change - penny) >= 0)
        {
            change = change - penny;
            coins += 1;
        }
    }
    printf("%d", coins);
    printf("\n");
}

It works with numbers 1, 1.5, 2, 2.5 and some others which are nicely rounded, but as soon as i type another number like 0.41 it stops right there.

What is the issue?

1 Answer 1

0

To be exact, it works for multiples of 0.25, because a floating point number always stores a multiple of a power of two. For 0.41, there is no finite representation in that way, the exact binary representation would have an infinite number of digits. So after cutting the stream of binary digits off, the final value will be slightly lower or higher than the intended value, meaning it's unlikely you end up at zero.

So one way of dealing with this is changing from floating-point to fixed-point. Fixed-point means you use integers to store numbers with a given absolute precision. For storing a number with up to three digits after decimal point, you'd store 1000 times the number (and remember that value in memory means multiples of 0.001). In our case here, that would be the factor 100, representing the number of cents in the change. We would also have to multiply all the values we want to subtract, turning 0.01 into 1. Kind of like percents work, the % symbol (not C's % operator) meaning hundredth.

Another approach is to add "margins", but that approach might be less robust.

BTW, if you switch to integer, you can use / and % operators to remove the loop. But most important to get it working.

You must log in to answer this question.

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