0

当我将一些数字添加到 Integer 的最大值时出现问题,我不再高于最大值,因为数字更改为 Integer.MIN_VALUE + 加值 -1,我应该如何检查它?`

        int max = Integer.MAX_VALUE;
        int x = max +100;
        if (x > max){
            System.out.println(x + "x is not bigger, so it wont be printed.");

        }


    }
}`
4

2 回答 2

1

有几种方法取决于你想要做什么。

  1. 如果您想向 an 添加一个数字int并想知道它是否溢出,请使用Math.addExact. ArithmeticException如果你想采取行动,它会抛出一个你可以抓住的。

  2. 如果您想安全地添加一个值,然后进行比较,请Integer.MAX_VALUE使用 along代替。根据定义 noint永远大于最大值。

所以我建议

try {
    int x = Math.addExact(Integer.MAX_VALUE, 100);
} catch (ArithmeticException ex) {
    System.out.println("x has overflowed");
}
于 2020-02-23T23:36:03.573 回答
0

一种方法是长期测试它。

            int max = 2292292;
            int x = 100;
            if ((x + (long)max) != (x + max)) {
                System.out.println("Overflow on x so it wont be printed.");
            } else {
                x = max + 100; 
            }

于 2020-02-23T23:29:12.097 回答