views:

230

answers:

5

I was writing this code in C when I encountered the following problem.

#include <stdio.h>
int main()
{
   int i=2;
   int j=3;
   int k,l;
   float a,b;
   k=i/j*j;
   l=j/i*i;
   a=i/j*j;
   b=j/i*i;
   printf("%d %d %f %f\n",k,l,a,b);
   return 0;
}

Can anyone tell me why the code is returning zero for the first and third variables (k and a)?

+10  A: 

Are you asking why k and a show up as zero? This is because in integer division 2/3 = 0 (the fractional part is truncated).

bobbymcr
Expanding on that, when you write "a = <expr>;" with "a" declared float, it is only the *result* of <expr> that is casted to float. Since all the values and variables in your expressions are integer, the results are all based on integer arithmetic.
Steve314
This goes for a as well, because he's doing the same operation there (i/j == (int)2/(int)3 == 0)
T.E.D.
+2  A: 

If you're asking why k and a are 0: i/j*j is the same as (i/j)*j. Since j is larger than i, i/j is 0 (integer division). 0*j is still 0, so the result (k) is 0. The same applies to the value of a.

sepp2k
+3  A: 

this is due to how the c compiler treats int in divisions:

 #include <stdio.h>
int main()
{
int i=2;
int j=3;
int k,l;
float a,b;
k=i/j*j; // k = (2/3)*3=0*3=0
l=j/i*i; // l = (3/2)*2=1*2=2
a=i/j*j; // same as k
b=j/i*i; // same as b
printf("%d %d %f %f/n",k,l,a,b);
return 0;
}
Am
+4  A: 

You haven't said what you're getting or what you expect, but in this case it's probably easy to guess. When you do 'a=i/j*j', you're expecting the result to be roughly .2222 (i.e. 2/9), but instead you're getting 0.0. This is because i and j are both int's, so the multiplication and (crucially) division are done in integer math, yielding 0. You assign the result to a float, so that 0 is then converted to 0.0f.

To fix it, convert at least one operand to floating point BEFORE the division: a = (float)i/j*j);

Jerry Coffin
+5  A: 

What I think you are experiencing is integer arithmetic. You correctly suppose l and b to be 2, but incorrectly assume that k and a will be 3 because it's the same operation. But it's not, it's integer arithmetic (rather than floating-point arithmetic). So when you do i / j (please consider using some whitespace), 2 / 3 = 0.33333... which is cast to an int and thus becomes 0. Then we multiply by 3 again, and 0 * 3 = 0.

If you change i and j to be floats (or pepper your math with (float) casts), this will do what you expect.

Chris Lutz