0

I have good number of coins for number over 1 with decimal (ex: 2.7, 5.1). And wrong number of coins only with numbers between 0 to 1 (0.99 or 0.41): always 0. plus the check50 says that it doesn't work with 4.2! Please could you hint me what could be my error because I have the integer already so I have no ideas. here is my code :

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

int main (void)

{
    int conversion;
    float change;
    int amount = 0;

    do 
    {
        printf("O hai! How much change is owed ?");
        change = get_float(); 

    }
    while (change < 0);

    conversion = (int) change * 100;


    while (conversion >= 25)
    {
        amount ++;
        conversion = conversion - 25;
    }

    while (conversion >= 10)
    {
        amount ++;
        conversion = conversion - 10;
    }

    while (conversion >= 5)
    {
        amount ++;
        conversion = conversion - 5;
    }

    while (conversion >= 1)
    {
        amount ++;
        conversion = conversion - 1;
    }

    printf("%d\n", amount);

 } 

thanks a lot.

1 Answer 1

0

A quick peak at the Hints section in the spec might help you identify the problem.

Do beware the inherent imprecision of floating-point values. [...] And take care to round your cents (to the nearest penny); don’t "truncate" (i.e., floor) your cents!

In your program, you don't round your cents - you instead just multiply the float (change) by 100, and then convert that to an int. But what about the small imprecision of floating-point values, like the spec said? Try printing a float's value to 55 decimal places. You can use the spec's example:

float f = 0.1;
printf("%.55f\n", f);

What does this print? 0.1000000014901161193847656250000000000000000000000000000! We expect it to print 0.1 then a whole bunch of zeros, right? Clearly, there is an imprecision! That's why it is so important that you use a function like roundf (in the math.h library), which rounds to the nearest integer.

If this answers your question, please hit the green checkmark. If you still have issues, comment below.

You must log in to answer this question.

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