0

I have written the following code as a part of for . I always seem to get a number less than the actual number of coins.Please help me out.

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

int main(void)
{
    int n=0, x;
    float c;
    do
    {
        printf("O hai! How much change is owed?\n");
        c=GetFloat();

        if((c/0.25)>=1)
        {
            x=c/0.25;
            n=n+x;
            c=c-(x*0.25);
        }
        if((c/0.10)>=1)
        {
            x=c/0.10;
            n=n+x;
            c=c-(x*0.10);
        }
        if((c/0.05)>=1)
        {
            x=c/0.05;
            n=n+x;
            c=c-(x*0.05);
        }

        n=n+(c*100);

    }while(c<=0);
    printf("%i\n", n);
}
3

You are not learning what this pset is trying to teach you. That the floats in your computer are stored imprecisely. Take a look at the following program:

float_test.c

#include "stdio.h"
#include "cs50.h"

int main(void)
{
    float number;
    number = GetFloat();

    printf("%.25f\n", number);
}

And now take a look at its output, for input 0.51. (any number would be the same)

night@hawk:~$ ./float_test
0.51
0.5099999904632568359375000
1

See that the 0.51 I gave, is not stored as 0.51, but as 0.5099999904632568359375000 if I print the first 25 decimal digits. That's the reason you are supposed to use integers instead of floats.


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

| improve this answer | |

You must log in to answer this question.

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