Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to int implicit vs explicit (cast) discrepancy

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
  1. Why would implicit and explicit conversion results be different?
  2. I would like results to be like the ones for implicit conversion, but without compilation warning. Is it possible?

Platform is Windows7, VS2010 or 2013.

like image 606
grunt Avatar asked Mar 15 '16 16:03

grunt


1 Answers

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.

like image 111
Bathsheba Avatar answered Oct 03 '22 14:10

Bathsheba