gpt4 book ai didi

Java 除以零不会抛出 ArithmeticException - 为什么?

转载 作者:行者123 更新时间:2023-12-02 03:35:45 25 4
gpt4 key购买 nike

为什么这段代码不抛出ArithmeticException?看看:

public class NewClass {

public static void main(String[] args) {
// TODO code application logic here
double tab[] = {1.2, 3.4, 0.0, 5.6};

try {
for (int i = 0; i < tab.length; i++) {
tab[i] = 1.0 / tab[i];
}
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException occured!");
}
}
}

最佳答案

IEEE 7541.0/0.0 定义为 Infinity,将 -1.0/0.0 定义为 -Infinity,将 0.0/0.0 定义为 NaN。

顺便说一句,浮点值也有 -0.0,因此 1.0/-0.0-Infinity

整数算术没有任何这些值,而是抛出异常。

要检查所有可能产生非有限数的可能值(例如 NaN、0.0、-0.0),您可以执行以下操作。

if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
throw new ArithmeticException("Not finite");

关于Java 除以零不会抛出 ArithmeticException - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56862942/

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