gpt4 book ai didi

java - 混合 float 和长计算产生错误答案,没有编译器警告

转载 作者:行者123 更新时间:2023-11-30 07:21:00 24 4
gpt4 key购买 nike

下面的代码输出错误的 startTime 值是不是很奇怪?

public class Temp {
public static void main(String args[]){
float duration = (float) 2.0;
long endTime = 1353728995;
long startTime = 0;
startTime = (long) (endTime - duration);
System.out.println(startTime);
}
}

最佳答案

它不会输出错误 值。它只是输出一个您不期望的值。

重要的是这里发生了什么:

endTime - duration

实际上评估为:

(float) endTime - duration;

这就是数据丢失的地方。最近的float 1353728995 的值为 1353729024,最接近 float减去 2 的结果仍然是 1353729024。

这一切都遵循语言规范。 JLS section 15.8.2 (加法运算符)声明二进制数字提升应用于操作数。

Section 5.6.2 (binary numeric promotion)像这样开始:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  • If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  • 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.

    • ...

因此,遵循这些规则,long endTime 的值转换为 float ,然后在float中执行减法算术。

记住 float只提供了 7 位有效数字的准确度,我希望其余的都相当明显。

请注意,没有将结果转换为 long ,编译器使发生的事情更清楚:

Test.java:8: error: possible loss of precision
long startTime = endTime - duration;
^
required: long
found: float
1 error

这很清楚结果将是 float ,这应该已经就操作将如何执行以及预期的准确性发出了警告。

关于java - 混合 float 和长计算产生错误答案,没有编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13612747/

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