-->

在Java中分割双零[复制](Dividing a double by zero in Java [

2019-09-20 03:46发布

可能重复:
为什么由0.0分的时候没有的Java抛出异常?

为什么在Java中,下面的语句将不报告ArithmeticException?

double d = 1.0/0;

Answer 1:

In short: floating point numbers can represent infinity (or even operations that yield values which aren't numbers) so an operation that results in this (e.g. dividing by 0) is valid.

Expanding upon Mohammod Hossain's answer, as well as this question and its accepted answer, an ArithmeticException is thrown "Thrown when an exceptional arithmetic condition has occurred". For integers, dividing by 0 is such a case, but for floating point numbers (floats and doubles) there exist positive and negative representations.

As an example,

public class DivZeroFun {

    public static void main(String args[]) {

        double f = 5.0;
        System.out.println(f / 0);
        double f2 = -5.0;
        System.out.println(f2/0);
    }
}

This code will print "Infinity" and then "-Infinity" as its answers, because "Infinity" is actually an accepted value for floats and doubles that is encoded in Java.

Also, from this forum post:

Floating point representations usually include +inf, -inf and even "Not a Number". Integer representations don't. The behaviour you're seeing isn't unique to Java, most programming languages will do something similar, because that's what the floating point hardware (or low level library) is doing.

and again from the forum post:

Because the IEEE standard for floating point numbers used has defined values for positive and negative infinity, and the special "not a number" case. See the contants in java.lang.Float and java.lang.Double for details.



文章来源: Dividing a double by zero in Java [duplicate]