为什么这种分工导致零? [英] Why does this division result in zero?
问题描述
我是C语言编写本code时,我遇到了以下问题。
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;
}
谁能告诉我为什么code是回零的第一个和第三个变量( K
和 A
)?
推荐答案
我认为你遇到的是的整数运算的。您正确地假设→
和 B
为2,但错误地认为 K
和 A
将在3,因为它是相同的操作。但它不是,它是整数运算(而不是浮点运算)。所以,当你做 I / J
(请考虑使用一些空白),2/3 = 0.33333 ...的这是强制转换为 INT
的,从而变为0。然后,我们乘以3一遍,0 * 3 = 0。
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.
如果您更改 I
和Ĵ
是浮动
S(或花椒你的数学与(浮点)
蒙上),这会做你期望的。
If you change i
and j
to be float
s (or pepper your math with (float)
casts), this will do what you expect.
这篇关于为什么这种分工导致零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!