请检查下面的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
解释这种行为
谢谢
最佳答案
start + d + end
的值太大,无法用 int
表示,但又不太大,无法用 long 表示
或双
。
通过使用+ 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.
关于java - Java long 和 double sum 的转换总是给出相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61795572/