This question already has answers here:
How can I check if multiplying two numbers in Java will cause an overflow?
(14个回答)
2年前关闭。
整数a = 200000;
双倍b =(双倍)(a * a);
我想能够计算(aa)(整数)是否已经太大(stackOverflow)以至于无法容纳在变量中;在这种情况下,我知道乘(aa)会导致一个不适合的int->数字将是错误的;
我不明白的是,我该如何计算呢?如何查看一个值是否不适合int变量?
是否可以通过仅使用普通代码和常识来不使用方法来执行此操作? ;-)
最好的祝福,
伍特
另一个
(14个回答)
2年前关闭。
整数a = 200000;
双倍b =(双倍)(a * a);
我想能够计算(aa)(整数)是否已经太大(stackOverflow)以至于无法容纳在变量中;在这种情况下,我知道乘(aa)会导致一个不适合的int->数字将是错误的;
我不明白的是,我该如何计算呢?如何查看一个值是否不适合int变量?
是否可以通过仅使用普通代码和常识来不使用方法来执行此操作? ;-)
最好的祝福,
伍特
最佳答案
可能的解决方案:
int a = 200000;
try {
int result = Math.multiplyExact(x, y);
} catch(ArithmeticException e) {
//if you get here, it is too big
}
另一个
long test = (long)a*(long)a;
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
// Overflow!