在数学中,规定被除数不能为0
那么在Java程序中一旦出现除数为0时,会出现什么情况呢:
对于除数a和被除数b (b=0),
(1)如果二者均为int型(long也算是int型),结果会抛出异常:java.lang.ArithmeticException: / by zero
(2)如果其中有一个为double或者float型,结果则是Infinity
另外,对于Double和Float的NaN/Infinity等是否相等呢:
Float.NaN == Double.NaN false
Float.NEGATIVE_INFINITY == Double.NEGATIVE_INFINITY true
Float.POSITIVE_INFINITY == Double.POSITIVE_INFINITY true
代码如下:
public class DivideZeroTest {
public static void main(String[] args) {
float f1 = 1;
double d1 = 1;
int i1 = 1;
int i0 = 0;
double f0 = 0;
double d0 = 0;
try {
System.out.println(i1 / i0);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(i1 / f0);
System.out.println(i1 / d0);
System.out.println(f1 / i0);
System.out.println(f1 / f0);
System.out.println(f1 / d0);
System.out.println(d1 / i0);
System.out.println(d1 / f0);
System.out.println(d1 / d0);
System.out.println(Float.NaN == Double.NaN);
System.out.println(Float.NEGATIVE_INFINITY == Double.NEGATIVE_INFINITY);
System.out.println(Float.POSITIVE_INFINITY == Double.POSITIVE_INFINITY);
}
}