0

I'm trying to create a solution for pset1 cash.c, the code below is not meant to be the final implantation, just a cursor to figure out the problem. When I run this code it works for values .01 to .05 but when I input anything higher that requires pennys the program fails to count the pennies. You can run this only in the cs50 IDE. Please help.

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

int main(void)
{
    float q = 0.25;
    float d = 0.1;
    float n = 0.05;
    float p = 0.01;
    int qu = 0;
    int du = 0;
    int nu = 0;
    int pu = 0;

    float f = get_float("Change owed: ");

    while (f >= q)
    {
        f = f - q;
        qu++;
    }

    while (f >= d)
    {
        f = f - d;
        du++;
    }

    while (f >= n)
    {
        f = f - n;
        nu++;
    }

    while (f >= p)
    {
        f = f - p;
        pu++;
    }
    printf("quarters: %i, dimes: %i, nickles: %i, pennys: %i\n", qu, du, nu, pu);
}

1 Answer 1

1

More accurately, it isn't counting pennies correctly. In fact, it isn't counting a lot of things correctly. (Try $4.20) The cause of the problem is the whole purpose of this pset. Because of that, I'll suggest going back and reviewing the class lectures and other material related to the inaccurate storage of floats.

Hint: try printing out the value of f to 12 or more digits of precision.

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.