英文:
Why long literal can be assigned to float variable while float datatype uses less memory?
问题
浮点型使用32位,长整型使用64位。为什么编译器允许这样做呢?
float x = 5555555555555555555L;
英文:
float uses 32 bits and long uses 64 bits. Why is this allowed by the compiler then?
float x = 5555555555555555555L;
答案1
得分: 5
float
的取值范围比 long
要广泛。因此,虽然在这样的赋值情况下(从 long
赋值给 double
也一样),肯定会丢失精度,但总体大小已经是可表示的 - 因此不会因为超出范围而需要抛出异常,例如。
Java 语言规范(第 5.1.2 节)中指出:
> 从 int
到 float
的扩宽原始转换,或从 long
到 float
的扩宽原始转换,或从 long
到 double
的扩宽原始转换,可能会导致精度丢失 - 也就是说,结果可能会丢失一些最低有效位的值。在这种情况下,生成的浮点值将是整数值的正确舍入版本,使用 IEEE 754 最近舍入模式(§4.2.4)。
英文:
The range of float
is broader than the range of long
. So while you can certainly lose precision with an assignment like this (and can when assigning a long
value to double
too), the general magnitude is already representable - so there's never be a need to throw an exception due to it being out of range, for example.
The JLS (section 5.1.2) says this:
> A widening primitive conversion from int
to float
, or from long
to float
, or from long
to double
, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. 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 (§4.2.4).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论