如何检查在 Java 中将两个数字相乘是否会导致溢出? [英] How can I check if multiplying two numbers in Java will cause an overflow?
本文介绍了如何检查在 Java 中将两个数字相乘是否会导致溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想处理两个数字相乘导致溢出的特殊情况.代码如下所示:
I want to handle the special case where multiplying two numbers together causes an overflow. The code looks something like this:
int a = 20;
long b = 30;
// if a or b are big enough, this result will silently overflow
long c = a * b;
这是一个简化版本.在实际程序中,a
和 b
在运行时来自别处.我想要实现的是这样的:
That's a simplified version. In the real program a
and b
are sourced elsewhere at runtime. What I want to achieve is something like this:
long c;
if (a * b will overflow) {
c = Long.MAX_VALUE;
} else {
c = a * b;
}
你如何建议我最好地编码?
How do you suggest I best code this?
更新:a
和 b
在我的场景中总是非负的.
Update: a
and b
are always non-negative in my scenario.
推荐答案
Java 8 有 Math.multiplyExact
、Math.addExact
等,用于 int 和 long.这些会在溢出时抛出未经检查的 ArithmeticException
.
Java 8 has Math.multiplyExact
, Math.addExact
etc. for ints and long. These throw an unchecked ArithmeticException
on overflow.
这篇关于如何检查在 Java 中将两个数字相乘是否会导致溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文