I'm currently working on Greedy from problem set 1. When I run the CS50 check, everything works correctly except when with an input of 4.2. I know that this is related to how the float isn't rounded correctly. I've searched thoroughly for how to round it correctly but after several hours of reading others' suggestions, I'm still not receiving the correct value for 4.2. How can I round for my specific case? Here's what I have so far:

float amount;
    printf("How much change is owed? ");
    amount = GetFloat();
while (amount < 0);
int change = amount * 100;
  • I had exactly the same problem. Can anyone explain why it is exactly that even though the float being entered is 4.2, and even though my code multiplies that 4.2 by 100, the end result is 419 instead of 420 (resulting in an incorrect final result). Thanks! – user9511 Sep 10 '15 at 2:35

You'll want to use the round function on that amount*100. Given that it's simply a matter of syntax, I don't mind just telling you.

It's as simple as int rounded_number = round(other_number*100); (using your own variables, of course)

Be sure to #include the library where the round() function is defined. I'll leave that to you to find.

Hint: reference.cs50.net may help.

  • What if I round the number before multiplying by 100. Will the results be same? – user7990 Aug 2 '15 at 8:00
  • No. if you round (4.2) you get 4 because the round function rounds to the nearest integer. Then you would multiply 4 *100 = 400. If you round (4.2*100) you get 420. Which one do you think is correct? – curiouskiwi Aug 2 '15 at 8:02
  • Thanks, got it. – user7990 Aug 2 '15 at 8:12

You must log in to answer this question.

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