gpt4 book ai didi

java - Java 如何处理多种类型的精度?

转载 作者:行者123 更新时间:2023-12-01 18:06:12 25 4
gpt4 key购买 nike

在 Java 中,当我打印这样的内容时

System.out.println(1.0f*1l));

我得到的输出

1.0

或与

System.out.println(((byte)1)*'A');

我得到的输出

65

在这两种情况下,其中一种类型比另一种更大。 Long 是 64 位,而 float 是 32 位,字节是 8 位,而 char 是 16 位。尽管如此,Java 仍以较小的类型输出结果。这不会被认为是精度损失吗?

最佳答案

Java 语言规范提供了一个基于操作数类型来管理结果类型的规则列表。

特别是,第 4.2.4 节指出

If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

这解释了为什么float“战胜”了long

整数运算在第 5.6.2 节中进行了解释。具体来说,它说

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

• If either operand is of type double, the other is converted to double.

• Otherwise, if either operand is of type float, the other is converted to float.

• Otherwise, if either operand is of type long, the other is converted to long.

• Otherwise, both operands are converted to type int.

这就是为什么在第二个示例中结果 65 的类型为 int

关于java - Java 如何处理多种类型的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36249740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com