如何检查Java中的两个数字相乘是否会导致溢出? [英] How can I check if multiplying two numbers in Java will cause an overflow?

查看:262
本文介绍了如何检查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;

这是一个简化版本。在真实程序中, 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 数学对于int和long,.addExact 等。这些在溢出时抛出未经检查的 ArithmeticException

Java 8 has Math.multiplyExact, Math.addExact etc. for ints and long. These throw an unchecked ArithmeticException on overflow.

这篇关于如何检查Java中的两个数字相乘是否会导致溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆