Java中运行表达式return 1.0/0.0会发生什么?return 1/0会发生什么?

在Java中运行表达式:1.0 / 0.0,会有返回么?会不会抛出异常或者是编译器error?
那1/0呢?
① 浮点数除法,1.0/0.0不会抛出异常,值为Infinity。

This is another tricky question from Double class. Though Java
developer knows about the double primitive type and Double class,
while doing floating point arithmetic, they don’t pay enough attention
to Double.INFINITY, NaN, and -0.0 and other rules that govern the
arithmetic calculations involving them. The simple answer to this
question is that it will not throw ArithmeticExcpetion and return
Double.INFINITY.

② 整数除以0时会抛出ArithmeticException。

Exception in thread "main" java.lang.ArithmeticException: / by zero

补充:如何判断一个x是否为NaN or Infinity?
不能使用 return x == NaN,因为无论如何,返回均为false,即使x为NaN;
必须使用Doubl类的静态方法isNaN();
示例:

public class Main1 {

    public static void main(String[] args) {
            double x = Double.NaN;
            System.out.println(x == Double.NaN);
            System.out.println(Double.isNaN(x));
    }
}

输出:

false
true

对Infinity同理:

public class Main1 {

    public static void main(String[] args) {
            double x = 1.0 / 0.0;
            System.out.println(x == Double.NEGATIVE_INFINITY);
            System.out.println(x == Double.POSITIVE_INFINITY);
            System.out.println(Double.isInfinite(x));
    }
}

输出:

false
true
true

可以看出 1.0/0.0为POSTIVE_INFINITY,说明java里面0.0是+0.0。如果1.0/0.0由于默写原因导致符号反转了,上述代码将等到相反结果。为了避免符号带来的麻烦,提高程序鲁棒性,建议使用Double.isInfinite()

你可能感兴趣的:(Java)