Dividing Integers (& Casting Precedance)


Quiz:
What does the following code print:

int i,j;
float k;
i = 5;
j = 2;
k = i/j;
printf("%f\n",k);


That’s right: 2.00000.
Why?
Despite the fact that we’re assigning it to a floating point, the division is carried out as integer division, which drops the remainder. To properly perform floating point division, try one of the following:

k = (float) i/j;
k = ((float) i)/j;
k = i/(float) j;

Note that the first line is NOT the same as:

k = (float) (i/j);

Putting the operation in parentheses will have it revert to integer division! Instead, because the cast attaches itself to the i before the division (casting has a higher priority than division), the first line from the acceptable solutions and the second are the same thing. Any of the acceptable solutions force a division between a float and an int, which is done as a floating point division.


Leave a Reply

Your email address will not be published. Required fields are marked *