gpt4 book ai didi

java - 当我不能使用 Integer 时,为什么 Java 不告诉我?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:50 25 4
gpt4 key购买 nike

对于一个小项目(第 10 题欧拉项目),我试图求和所有低于 200 万的素数。所以我使用了一种蛮力方法并从 0 迭代到 2'000'000 并检查该数字是否为质数。如果是,我将其添加到总和中:

private int sum = 0;

private void calculate() {
for (int i = 0; i < 2000000; i++) {
if (i.isPrime()) {
sum = sum + i;
}
}
sysout(sum)
}

此计算结果为 1179908154,但这是不正确的。所以我将 int 更改为 BigInteger,现在我得到了正确的总和 142913828922。显然 int 的范围溢出了。但为什么 Java 不能告诉我呢? (例如通过异常(exception))

最佳答案

因为可以想象,您可能希望它以传统的 Integer 方式运行。异常(exception)是为绝对错误和不可挽回的错误保留的。

ETA:来自语言规范:

"The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception (§11) are the integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3), which throw an ArithmeticException if the right-hand operand is zero."

( http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html )

关于java - 当我不能使用 Integer 时,为什么 Java 不告诉我?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2834248/

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