Why does int / float multiplication produce different results?

If I multiply the value of float and integer as shown below, why do all the multiplications produce a different result? My expectation was a consistent result. I thought that in both cases the int value is implicitly converted to a float before multiplication. But there seems to be a difference. What is the reason for this difference?

int multiply(float val, int multiplier) { return val * multiplier; } int multiply2(float val, int multiplier) { return float(val * multiplier); } float val = 1.3f; int result0 = val * int(10); // 12 int result1 = 1.3f * int(10); // 13 int result3 = multiply(1.3f, 10); //12 int result4 = multiply2(1.3f, 10); // 13 

Thanks. Thorsten

+7
c ++ floating-point multiplication
source share
1 answer

Most likely for you:

Assuming that IEEE or similar floats 1.3 cannot be represented and probably something like 1.299999, which is multiplied by 10, is 12.99999, which is then truncated to int is 12.

However, 1.3 * 10 can be evaluated at compile time, which is likely to lead to an accurate representation of 13.

Depending on how your code is really structured, which compiler is used and what parameters it is used with, it can evaluate from one to 12 or 13, depending on whether it is executed at startup or compilation time.

For completeness, with the following code, I could reproduce it:

 extern int result0; extern int result1; float val = 1.3f; void foo( ) { result0 = val * int(10); // 12 result1 = 1.3f * int(10); // 13 } 
+8
source share

All Articles