Why long literal can be assigned to float variable while float datatype uses less memory?

huangapple go评论80阅读模式
英文:

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 节)中指出:

> 从 intfloat 的扩宽原始转换,或从 longfloat 的扩宽原始转换,或从 longdouble 的扩宽原始转换,可能会导致精度丢失 - 也就是说,结果可能会丢失一些最低有效位的值。在这种情况下,生成的浮点值将是整数值的正确舍入版本,使用 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).

huangapple
  • 本文由 发表于 2020年10月18日 13:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64410174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定