简体   繁体   中英

double d=1/0.0 vs double d=1/0

double d=1/0.0;
    System.out.println(d);

It prints Infinity , but if we will write double d=1/0; and print it we'll get this exception: Exception in thread "main" java.lang.ArithmeticException: / by zero at D.main(D.java:3) Why does Java know in one case that diving by zero is infinity but for the int 0 it is not defined? In both cases d is double and in both cases the result is infinity.

Floating point data types have a special value reserved to represent infinity, integer values do not.

In your code 1/0 is an integer division that, of course, fails. However, 1/0.0 is a floating point division and so results in Infinity .

strictly speaking, 1.0/0.0 isn't infinity at all, it's undefined.

As David says in his answer, Floats have a way of expressing a number that is not in the range of the highest number it can represent and the lowest. These values are collectively known as "Not a number" or just NaNs. NaNs can also occur from calculations that really are infinite (such as lim x -> 0 ln 2 x ), values that are finite but overflow the range floats can represent (like 10 100 100 ), as well as undefined values like 1/0.

Floating point numbers don't quite clearly distinguish among undefined values, overflow and infinity; what combination of bits results from that calculation depends. Since just printing "NaN" or "Not a Number" is a bit harder to understand for folks that don't know how floating point values are represented, that formatter just prints "Infinity" or sometimes "-Infinity" Since it provides the same level of information when you do know what FP NaN's are all about, and has some meaning when you don't.

Integers don't have anything comparable to floating point NaN's. Since there's no sensible value for an integer to take when you do 1/0, the only option left is to raise an exception.

The same code written in machine language can either invoke an interrupt, which is comparable to a Java exception, or set a condition register, which would be a global value to indicate that the last calculation was a divide by zero. which of those are available varies a bit by platform.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM