Search code examples
cdivisioninteger-division

Why does this division result in zero?


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)?


Solution

  • 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.