【发布时间】:2012-09-10 08:42:54
【问题描述】:
我在检测两个数字的和/乘是否超过长整数的最大值时遇到问题。
示例代码:
long a = 2 * Long.MAX_VALUE;
System.out.println("long.max * smth > long.max... or is it? a=" + a);
这给了我-2,而我希望它会抛出一个NumberFormatException...
有没有一种简单的方法来完成这项工作?因为我有一些代码在嵌套的 IF 块中进行乘法运算或在循环中进行加法运算,我不想在每个 IF 或循环内添加更多的 IF。
编辑:哦,好吧,似乎另一个问题的这个答案最适合我的需要:https://stackoverflow.com/a/9057367/540394
我不想装箱/拆箱,因为它增加了不必要的开销,而且这种方式很短,这对我来说是一个巨大的优势。我将编写两个简短的函数来执行这些检查并返回最小或最大长度。
Edit2:根据我上面链接的答案,这是将 long 限制为其最小值/最大值的函数:
/**
* @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 Long.MIN_VALUE or more than Long.MAX_VALUE
*/
public static long limitLong(long a, long b, long c)
{
return (((a > 0) && (b > 0) && (c <= 0))
? Long.MAX_VALUE
: (((a < 0) && (b < 0) && (c >= 0)) ? Long.MIN_VALUE : c));
}
如果您认为这是错误的,请告诉我。
【问题讨论】:
-
+1。应该有一些允许整数溢出检测的库。
-
或特殊块(类似于 finally?),可以帮助开发人员为在其中执行的所有数学代码启用溢出错误行为。我相信 C# 有一个。编辑:找到了,checked and unchecked blocks in C#。
-
好吧,C# 似乎在溢出时抛出错误(我更喜欢沉默和对我没有意义的错误结果)...
-
添加了检查最小/最大溢出的功能,有人可以检查一下吗?