mikeage.net Logo

mikeage.net @ ט׳ שבט תשפ״ג

Dividing Integers (& Casting Precedance)

What does the following code print:

int i,j;
float k;
i = 5;
j = 2;
k = i/j;

That's right: 2.00000.
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): 4194304/4194304
Memory(FALSE): 3034784/3044744