java - Java long 和 double sum 的转换总是给出相同的结果

标签 java casting integer-overflow

请检查下面的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/

相关文章:

java - kafkastreams - 增加更多的处理能力

swift - 将字符串转换为数字、格式;除非不能转换,则 string=string

c - *( char** ) 实现什么类型的转换?

python - Python 中使用 numpy 数组进行高效的逐元素乘法

java - 自动过期并删除SQLite数据库中的记录

java - 为什么 'Arrays class'有重载方法

java - JButton ActionListener 两人游戏

java - 将子类转换为等于父类(super class)时转换失败

go - 原子 AddUint32 溢出

c - clang 中是否有 'Integral constant overflow' 警告?