在 java 中,隐式转换的层次结构是
byte -> short -> int -> long -> float -> double
Long 可以容纳 8 个字节的数据。那么为什么它被隐式类型转换为只能容纳 4 个字节的 float 而不是可以容纳 8 个字节的 double。为什么它不被视为窄化?
哪些基本类型将被隐式转换为 char ?
最佳答案
这与使用了多少位数据无关。这是关于可以表示的规模。
来自 JLS section 5.1.2 (widening primitive conversions) :
A widening primitive conversion does not lose information about the overall magnitude of a numeric value.
...
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. 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).
long
的范围远小于float
的范围,但精度固定为1。float
的精度变化跨范围,就绝对值而言。换句话说,没有 long
超出 float
的范围,但有 long
值不能精确表示为float
值。
移动到 double
对此无济于事 - long
值也不能精确表示为 double
。
关于java - 类型转换 long 以隐式 float 而不是缩小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22067409/