1

In the report of check50, everything goes smoothly except for one value: 4.2. The correct answer is 18 while my program output 22. Could you help me find out which part goes wrong? Here's my code. int main(void) { float x; do { x = get_float("Please type in a number here: "); } while (x < 0);

int n = 0;
int c = x * 100;

if (c >= 25)
{
    n = c / 25;
    c = c % 25;
}
else
{

}

if (c >= 10)
{
    n = c / 10 + n;
    c = c % 10;
}
else
{

}

if (c >= 5)
{
    n = c / 5 + n;
    c = c % 5;
}
else
{

}


n = c / 1 + n;
c = c % 1;

printf("%i\n", n);

}

1

Three big hints:

How many coins in $4.19 ?

What happens to the decimal part of a number when you do INTEGER division?

When 4.20 is stored as a float, what is actually stored, accurate to 16 digits?

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

  • I understand where my problem arises. But still there are some confusions. 1. Take 4.20 as an example. When the program execute int c = x * 100, what is the output? Since the original floating-point input will be 4.19999...(if I didn't get it wrong), and variable c is a integer, will the output be 419? 2. My solution is to add an .001 to the right side of the equation (perhaps not equation?), while some suggest the "rounding" function. I've tried it, but it doesn't work. A question: Is the output of float roundf(float x); a float or an integer? Thanks for your patience. :) – bobby1208 Feb 26 '18 at 9:52
  • int c = x * 100; will return 419. X was 4.19999... so x * 100 = 419.999.... and when x is assigned to an int, it will truncate the decimal, storing 419 in c. Also, roundf returns a float. Exactly what was the code that you used? Which form of rounding function did you use? You do know that there are various forms that return different types, right? – Cliff B Feb 26 '18 at 10:15
0

In my code, which wasn't massively dissimilar to yours, changing from float to double solved the problem.

You must log in to answer this question.

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