Java sum 2 negative numbers

天大地大妈咪最大 提交于 2019-12-11 05:05:29

问题


I'm trying to convert a function in java to pl/pgsql, and one problem that I found is when I'm trying to sum 2 negative numbers, and a get a positive number, more specifically :

public void sum(){
    int n1 = -1808642602;
    int n2 = -904321301;
    System.out.println(n1 + n2);// result is 1582003393
}

And in pl/pgsql I get an integer out of range error, and if I change the variables type to bigint i get a normal sum of 2 negative numbers, that is -2712963903, instead of 1582003393

How do I do to pl/pgsql get the same result without printing an integer out of range error?


回答1:


This happens because the Java int underflows and doesn't tell you.

To get the answer you are looking for in pl, you need to use bigint. Then detect the case when the result is less than Java Integer.MIN_INT (-2^31), which is the case where Java will give a positive result. To get what Java would give you, add 2^32.




回答2:


You are overflowing the int try the same thing with long and it should work.




回答3:


It's overflowing, because the result is too big for an int. Use long instead.




回答4:


Java sums them as 32 bit signed integers, which wrap at -231. Have you tried a 64 bit long instead?




回答5:


That valid rand of int in Java is -2,147,483,648 to 2,147,483,647 (-2^31 - 2^31-1).

You are causing an Integer underflow. You should use a type long instead of int which ranges from -2^63 to 2^63-1




回答6:


Java treats those 2 numbers as signed integers. Basically the scope for singed integers is -2,147,483,648 to 2,147,483,647 (-2^31 - 2^31-1). Hence the sum of those to values is -2712963903 which is less than the the minimum -2^31 so underflows and then wraps around by doing 2^32 - 2712963903 which gives you the signed int 1582003393.




回答7:


Try using a long which will not overflow in this case (but will for large enough numbers)

System.out.println((long) n1 + n2);


来源:https://stackoverflow.com/questions/5121698/java-sum-2-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!