mikeage.net Logo
mikeage.net/2006/10/17/dividing-integers-casting-precedance/

mikeage.net @ ט״ז תשרי תשע״ט

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

Quick Map
Content +
Personal +
Archives +
Site Stuff +
RBS Weather +
Search +
Recent Images

Valid XHTML 1.1!
Printer Friendly Page
 

Last Modified: September 04, 2006 @ 02:11 CST

Memory(TRUE): 2097152/2097152
Memory(FALSE): 2987824/2997808