简体   繁体   English

低于long的最大值的整数总和是否为负?

[英]Sum of ints below long's max value returns negative?

I have 5 objects, a , b , c . 我有5个对象, abc d and e . de The 5 objects hashcodes are as follows: 5个对象的哈希码如下:

a => 72444
b => 110327396
c => 107151
d => 2017793190
e => 68574749

As you can see, all are positive values. 如您所见,所有都是正值。 However, when I sum them up into a long -variable, the result comes out negative: 但是,当我将它们总结为一个long变量时,结果为负数:

long sum = a+b+c+d+e;
System.out.println(sum);     // prints -2098092366

The sum of these ints far below the max-value of long (9223372036854775807), yet it yields a negative result. 这些整数的总和远低于long的最大值(9223372036854775807),但得出的结果是负数。 Why? 为什么?

That happens because your variables are all int s, so you to int addition (which overflows), and then the final result is converted to long . 发生这种情况是因为您的变量都是int ,所以您将int加法(溢出),然后将最终结果转换为long

You can fix this by casting the first variable to long : 您可以通过将第一个变量转换为long来解决此问题:

long sum = (long)a + b + c + d + e;

Integer values can be -2,147,483,648 to 2,147,483,647. 整数值可以是-2,147,483,648到2,147,483,647。 The sum actually exceeds the max value and trancted for numeric overflow . 该总和实际上超过了最大值,并因numeric overflow而减半。

int x = 2147483647;
x++;
System.out.println(x);

It prints - -2147483648 打印-2147483648

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM