我试图理解下面的代码的行为,我写的实验计算溢出.
public static void main(String[] args) {
System.out.println(getSomeValue());
System.out.println(getFixedSomeValue());
}
private static double getSomeValue() {
return (2500000 - 0) * 250000 * (200 + 310);
}
private static double getFixedSomeValue() {
return (double) (2500000 - 0) * 250000 * (200 + 310);
}
Run Code Online (Sandbox Code Playgroud)
输出:
-9.9787264E8
3.1875E14
Run Code Online (Sandbox Code Playgroud)
我所理解的是:可能是因为整数溢出:
Double.MAX_VALUE = 1.7976931348623157E308
Integer.MAX_VALUE = 2147483647
Run Code Online (Sandbox Code Playgroud)
我不明白为什么值不同?当方法的返回类型为double时,是否应该自动将其转换为double?
(2500000 - 0) * 250000 * (200 + 310)是一个由int文字和数字运算符组成的表达式,因此它使用整数运算符进行求值,结果为a int,因此溢出(因为它受限于Integer.MAX_VALUE).溢出的结果double在方法返回之前转换为,但为时已晚.
当您(double)在开头添加时,转换(2500000 - 0)为double并避免数字溢出,因为现在所有运算符都是导致double值的浮点运算符.这与写作类似
return (2500000.0 - 0) * 250000 * (200 + 310)
^ decimal point = double literal rather than int
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |