Originally Posted by
loongkee
Code:
float fnCalcAvg( int x , int y )
{
float average;
average= (x+y)/2;
return(average);
}
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.
If you want the calculation done using floating point, you have to force conversion to float before doing the division. Options might include
Code:
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. */
or
Code:
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 */
or
Code:
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 */
There are many other possibilities.