int i1 = 0, i2 = 0;
float f = 2.8f;
i1 += f;
i2 += (int)f;
f += 0.1;
i1 += f;
i2 += (int)f;
f += 0.1;
i1 += f;
i2 += (int)f;
printf("%d %d\n", i1, i2);
Output:
7 6
Platform is Windows7, VS2010 or 2013.
To analyse this, the first job is to rewrite a += b
as a = a + b
.
i + (int)f
will be computed in integer arithmetic due to the explicit cast.
But i + f
will be computed in floating point arithmetic due to type promotion.
So the expressions have different types. Due to the way floating point works, the result, when converted back to an int
could differ.
The moral of the story is to not use +=
for mixed types, and to not ignore helpful compiler warnings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With