0

Why does this give 19 instead of 20 when change = 4.2? Thanks.

enter image description here

1

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.

The (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.

1
  • Thanks Blauelf for your clear explanation. – user9891471 Jan 9 '19 at 18:24

You must log in to answer this question.

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