[英]Converting int/long zero to double
Considering this code snippet: 考虑此代码段:
int i = 0;
double d1 = (double) i;
long l = 0L;
double d2 = (double) l;
Running this on my machine prints 0.0
for both conversions. 在我的机器上运行它会为两次转换打印0.0
。 But can d1
and d2
ever be anything but 0.0
? 但d1
和d2
可以是0.0
吗?
As I understand, this is a widening primitive conversion to which the spec says : 据我了解,这是一个扩展的原始转换 , 规范说 :
A widening primitive conversion does not lose information about the overall magnitude of a numeric value. 扩展的原始转换不会丢失有关数值总体大小的信息。
as well as 以及
A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision 将int或long值扩展为float,或将long值转换为double,可能会导致精度损失
As I understand the spec, the above would mean that int 0
will always become double 0.0
but long 0
can be converted to something else (eg 1E-20
or something like that). 据我了解规范,上述意味着int 0
将始终变为double 0.0
但long 0
可以转换为其他东西(例如1E-20
或类似的东西)。 Is my spec interpretation correct? 我的规范解释是否正确?
The full quote is: 完整的报价是:
A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. 将int或long值扩展为float,或将long值转换为double,可能会导致精度损失 - 也就是说,结果可能会丢失该值的一些最低有效位。 In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode. 在这种情况下,使用IEEE 754舍入到最接近模式,得到的浮点值将是整数值的正确舍入版本。
(Emphasis mine) (强调我的)
This is covering the case where the int
/ long
value cannot be exactly represented in float
/ double
(in which case, the nearest representable value is chosen). 这涵盖了int
/ long
值无法在float
/ double
精确表示的情况(在这种情况下,选择最接近的可表示值)。 Clearly, 0
can be represented, so one would not expect a loss of precision. 显然, 0
可以表示,因此人们不会期望精度损失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.