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

Verification Image

Please type the letters you see in the picture. This field is case-insensitive, and valid letters are A-Z (no numbers)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Quicktags:

Quick Map
Content +
Personal +
Archives +
Site Stuff +
RBS Weather +
Search +
New Images
Visitors
Clustermap
Blogroll

Valid XHTML 1.1!
Printer Friendly Page
 

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