Why does this give 19 instead of 20 when change = 4.2? Thanks.
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
Welcome to the world of (binary) floating point. A value like
4.2 cannot be precisely represented in binary, it would be represented by an infinite sequence of binary digits. Obviously we don't have an infinite amount of RAM, so the number is cut off at some point, resulting in a binary number that's slightly above or below the value you wanted to express, you could consider this a rounding error.
(int) typecast truncates the value, removing fractional part, and
change * 100 likely is something like
419.999999... (just slightly below 420), so the result after conversion is 419 instead of 420. Now your modulo operator is applied to 419 :D
One way around this is using
round, found in
math.h. Another is adding
0.5 before the conversion, which does the same for positive numbers.