Java如何处理整数下溢和溢出?
在此之后,您将如何检查/测试这是否正在发生?
我在检测两个数字的和/乘以是否超过长整数的最大值时遇到问题.
示例代码:
long a = 2 * Long.MAX_VALUE;
System.out.println("long.max * smth > long.max... or is it? a=" + a);
Run Code Online (Sandbox Code Playgroud)
这给了我-2,而我希望它会抛出NumberFormatException......
是否有简单的方法使这项工作?因为我有一些代码在嵌套的IF块中进行乘法或在循环中添加,我不想在每个IF或循环内添加更多的IF.
编辑:哦,好吧,似乎从另一个问题的答案是最适合我需要的:https:
//stackoverflow.com/a/9057367/540394我不想做装箱/拆箱,因为它增加了不必要的开销,这种方式很短,这对我来说是一个巨大的优势.我将编写两个简短函数来执行这些检查并返回最小或最大长度.
Edit2:这是根据我上面链接的答案将长度限制为最小/最大值的功能:
/**
* @param a : one of the two numbers added/multiplied
* @param b : the other of the two numbers
* @param c : the result of the addition/multiplication
* @return the minimum or maximum value of a long integer if addition/multiplication of a and b is less than …Run Code Online (Sandbox Code Playgroud)