問題描述
我正在嘗試將 java 中的函數(shù)轉(zhuǎn)換為 pl/pgsql,我發(fā)現(xiàn)的一個(gè)問題是當(dāng)我嘗試將 2 個(gè)負(fù)數(shù)相加并得到一個(gè)正數(shù)時(shí),更具體地說:
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
}
在 pl/pgsql 中,我得到一個(gè)整數(shù)超出范圍錯(cuò)誤,如果我將變量類型更改為 bigint,我得到 2 個(gè)負(fù)數(shù)的正常總和,即 -2712963903,而不是 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
如何在不打印整數(shù)超出范圍錯(cuò)誤的情況下讓 pl/pgsql 獲得相同的結(jié)果?
How do I do to pl/pgsql get the same result without printing an integer out of range error?
推薦答案
發(fā)生這種情況是因?yàn)?Java int 下溢并且沒有告訴您.
This happens because the Java int underflows and doesn't tell you.
要在 pl 中獲得您要尋找的答案,您需要使用 bigint.然后檢測結(jié)果小于 Java Integer.MIN_INT (-2^31) 的情況,這是 Java 會(huì)給出肯定結(jié)果的情況.要獲得 Java 將提供的內(nèi)容,請?zhí)砑?2^32.
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.
這篇關(guān)于Java求和2個(gè)負(fù)數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!