首页 > 解决方案 > 为什么这不能正确检测整数溢出?

问题描述

为什么这不能正确检测整数溢出?

private static float calc(float a, int b){
    float sum = a;

    for (int i = 1; i <= b; i++){
        assert Math.abs(a) <= Integer.MAX_VALUE : "Overflow";
        sum = sum * sum;
    }
    return sum;
}

标签: javaassertassertion

解决方案


assert语句使用永远不会改变的变量a。它应该使用sum.

默认情况下,断言在运行时被禁用,因此您需要java使用-enableassertions(or -ea) 开关运行。

示例用法:

class TestOverflow<T> {

    public static void main(String[] args) {
        System.out.println(calc(2.0f, 6));
    }


    private static float calc(float a, int b){
        float sum = a;

        for (int i = 1; i <= b; i++){
            assert Math.abs(sum) <= Integer.MAX_VALUE : "Overflow";
            sum = sum * sum;
        }
        return sum;
    }
}

编译并运行:

$ java -ea -cp out/production/scratchpad/ TestOverflow 
Exception in thread "main" java.lang.AssertionError: Overflow
        at TestOverflow.calc(TestOverflow.java:12)
        at TestOverflow.main(TestOverflow.java:4)

推荐阅读