简体   繁体   中英

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

I have 5 objects, a , b , c . d and e . The 5 objects hashcodes are as follows:

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 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. 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 .

You can fix this by casting the first variable to long :

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

Integer values can be -2,147,483,648 to 2,147,483,647. The sum actually exceeds the max value and trancted for numeric overflow .

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

It prints - -2147483648

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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