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