转换 Java long 和 double sum 总是得到相同的结果

Casting Java long and double sum gives always same result

请检查下面这个Java代码:

public class Test{

  public static void main(String []args){
    long start = 1572544800000L;
    long end = 1635703200000L;
    int d = 10;
    int val = (int)(start + d + end + 0.0);
    // value 2147483647
    System.out.println("value: " + val); 
  }
}

在这里,如果我更改 d 的值,输出总是相同的 2147483647。这是 Int 最大值。 如果我将 0.0 更改为 0,则输出符合预期。

任何人都可以在 Java

中解释此行为

谢谢

2147483647 = Integer.MAX_VALUE

尝试

double val = (double)(start + d + end + 0.0);

或者,

long val = (long)(start + d + end + 0.0);

start + d + end 的值太大,无法用 int 表示,但又不太大,无法用 longdouble 表示。

通过使用 + 0.0,您将 start + d + end + 0.0 的整个表达式的类型设为 double。所以总的来说,你正在将 double 转换为 int.

当您将太大的 double 转换为 int 时会发生什么? Java Language Specification 5.1.3告诉你答案:

The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

如果你使用 0,但是,表达式 start + d + end + 0 的类型仍然是 long,所以你正在将 long 转换为 int ,这是一个不同的转换。它是这样发生的:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.