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

雨燕双飞 提交于 2019-12-23 17:38:14

问题


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.


回答1:


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.




回答2:


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 limx -> 0 ln2 x), values that are finite but overflow the range floats can represent (like 10100100), 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.



来源:https://stackoverflow.com/questions/7373280/double-d-1-0-0-vs-double-d-1-0

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