gpt4 book ai didi

java - 如何检查Java中的整数溢出?

转载 作者:行者123 更新时间:2023-12-01 17:47:42 25 4
gpt4 key购买 nike

int a = 200000;

双b = (双) (a*a);

我希望能够计算 (aa)(整数)是否已经太大(stackOverflow)而无法保存在变量中;在这种情况下,我知道乘法 (aa) 会导致一个不适合的 int -> 数字将是错误的;

我不明白的是我如何能够从我的头脑中计算出这个。如何查看某个值是否不适合 int 变量?

有没有一种方法可以在不使用方法的情况下,仅使用纯代码和常识来做到这一点? ;-)

最诚挚的问候,

沃特

最佳答案

两种可能的解决方案。

捕获调用 Math.…Exact 方法后抛出的异常:Math.multiplyExact , Math.addExact , Math.decrementExact ,等等。

 int a = 200000;

try {
int result = Math.multiplyExact(x, y);

} catch(ArithmeticException e) {
//if you get here, it is too big
}

或者,检查 minimum 的常量和 maximum可能的整数值。

 long test = (long)a*(long)a;
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
// Overflow!

关于java - 如何检查Java中的整数溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com