Java sum 2 negative numbers(Java求和2个负数)
问题描述
我正在尝试将 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个负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java求和2个负数


基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01