0

I was writing a code to calculate the minimum no. of coins required to return the change mentioned by the user. my code works on all test cases but returns 418 when i enter 4.20. this is the only problem i am facing and don't know what is wrong. here's my code-

#include <stdio.h>
#include <cs50.h>
int main(void)
{
float d;
int n = 0;
do
{
    d = get_float("Change owed: ");
}
while (d < 0.00);
d = d * 100;
while (d >= 25)
{
    n++;
    d -= 25;
}
while (d >= 10)
{
    n++;
    d -= 10;
}
while (d >= 5)
{
    n++;
    d -= 5;
}
while (d >= 1)
{
    n++;
    d -= 0.01;
}
printf("%d\n", n);
}
0
1

When you write

d -= 0.01;

do you mean

d -= 1;

?

Also, consider rounding after multiplication with 100. Decimal numbers like 4.2 might seem easy to write as a decimal number, but in binary that's an infinitely long number, so it's cut off after a few digits, resulting in a value slightly lower or slightly higher than the intended value.

1
  • 0.01 was a silly mistake. rounding off the number did the trick as it was returning 22 even after the initial correction. – Kuvam Devgan Dec 9 '18 at 12:56

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