将浮点数显式类型转换为字节

explicit typecast float to byte

从浮点数到字节的显式类型转换在 Java 中是如何工作的?为什么最后的输出也是 -1 而不是 0?第一个输出 57 可能是由于算术溢出,所以加 1 得到 58,这对我来说很有意义。但是因此我希望最后的输出是 0.

public class Typecasts {

    public static void main(String[] args) {

        float f = 12345.0f;
        byte b = (byte) f;
        System.out.println(b); // output: 57
        b = (byte) (f + 1);
        System.out.println(b); // output: 58
        f = 12345678987654321.0f;
        b = (byte) f;
        System.out.println(b); // output: -1
        b = (byte) (f + 1);
        System.out.println(b); // output: -1
    }

}

floatbyte 的转换是 缩小原始转换 ,根据 [=36],这可能会导致丢弃最重要的字节=] 语言规范§ 5.1.

然而,真正的问题在于:像 12345678987654321.0 这样的大数字已经 已经丢失了精度,甚至在执行类型转换之前。打印出 f 的值已经暗示了这一点:

1.23456795E16

参见Java 语言规范§ 4.2.3 和§ 4.2.4

Floating-point arithmetic is carried out in accordance with the rules of the IEEE 754 Standard, including for overflow and underflow.

此外,JLS § 15.4 定义了浮点表达式的执行方式。读起来有点技术性,但简而言之,它会丢弃最低有效位,因为 underflow.

因此,在您的情况下,f + 1 只会导致 f