开发者

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;
}

C开发者_运维知识库an anyone tell me why the code is returning zero for the first and third variables (k and 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).


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.


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


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;
}


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.


it doesn’t matter if you’re variable is float or not, as long you’re using

integer / integer , you’ll get 0,

but because you’re using a float output, you get 0.0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜