为何将int除以2会产生正确的值? [英] Why does dividing two int not yield the right value when assigned to double?
问题描述
下面的代码片段中的结果
How come that in the following snippet
int a = 7;
int b = 3;
double c = 0;
c = a / b;
c
最终具有值2,而不是人们所期望的2.3333。如果 a
和 b
是双打,答案的确变为2.333。但是可以肯定的是,由于 c
已经是双精度数,它应该使用整数吗?
c
ends up having the value 2, rather than 2.3333, as one would expect. If a
and b
are doubles, the answer does turn to 2.333. But surely because c
already is a double it should have worked with integers?
那么 int / int = double
不起作用?
推荐答案
这是因为您正在使用 operator /
的整数除法版本,它需要2个 int
s并返回 int
。为了使用 double
版本,该版本将返回 double
,其中至少一个 int
必须显式转换为 double
。
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
这篇关于为何将int除以2会产生正确的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!