x+y is computed using integer arithmetic, and then divided by 2, again using integer arithmetic (which will truncate, and any fractional part is lost). Only then, is the resultant integer converted to float, in order to store the value in average. The fact that average is of type float does not make the addition or the division occur using floating point.
Originally Posted by loongkee
If you want the calculation done using floating point, you have to force conversion to float before doing the division. Options might include
average = (x + y)/2.0f; /* 2.0f is of type float, so (x + y) is computed as an integer and then converted to float, before dividing by 2.0f. */
average = (x + y)/((float)2); /* converts int 2 to float explicitly. Since now dividing by float, the value of (x + y) is converted to float, before doing the division */
There are many other possibilities.
average = ((float)x + y)/2; /* x is converted to float explicitly. Because y is being added to a float, y is converted to float before doing the addition. Then (since ((float)x + y) is of type float, 2 is also converted to float, before doing the addition */