为什么将数字除以零会有如此不同的答案:
我的代码:
class Test {
public static void main(String[] args){
int a = (int)(3/0.0F);
System.out.println(a);
System.out.println(3/0.0F);
System.out.println(3/0);
}
}
输出:
2147483647
Infinity
Exception in thread "main" java.lang.ArithmeticException: / by zero
每次我将一个数字除以一个整数(byte、short、int、long)时,它都会抛出 ArithmeticException,而用实数(float、double)时则不会出现这种情况。为什么?
最佳答案
来自 JLS §15.17.2 :
- Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
除了:
if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.
关于java - 算术异常 :/by zero only works on integers in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24878815/