Dividing a double by zero in Java [duplicate]

梦想的初衷 提交于 2019-12-24 04:51:48

问题


Possible Duplicate:
Why doesn't Java throw an Exception when dividing by 0.0?

Why the following statement in Java will not report an ArithmeticException?

double d = 1.0/0;

回答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.



来源:https://stackoverflow.com/questions/11642601/dividing-a-double-by-zero-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!