以下语句显然会抛出 java.lang.ArithmeticException:/by zero
。
System.out.println(0/0);
因为文字 0
被认为是一个 int
文字,整数运算中不允许除以零。
以下情况不会抛出任何异常,例如 java.lang.ArithmeticException:/by zero
。
int a = 0;
double b = 6.199;
System.out.println((b/a));
它显示Infinity
。
以下语句毫无异常(exception)地产生 NaN
(非数字)。
System.out.println(0D/0); //or 0.0/0, or 0.0/0.0 or 0/0.0 - floating point arithmetic.
在这种情况下,两个操作数都被认为是 double 的。
同样,以下语句不会抛出任何异常。
double div1 = 0D/0; //or 0D/0D
double div2 = 0/0D; //or 0D/0D
System.out.printf("div1 = %s : div2 = %s%n", div1, div2);
System.out.printf("div1 == div2 : %b%n", div1 == div2);
System.out.printf("div1 == div1 : %b%n", div1 == div1);
System.out.printf("div2 == div2 : %b%n", div2 == div2);
System.out.printf("Double.NaN == Double.NaN : %b%n", Double.NaN == Double.NaN);
System.out.printf("Float.NaN == Float.NaN : %b%n", Float.NaN == Float.NaN);
它们产生以下输出。
div1 = NaN : div2 = NaN
div1 == div2 : false
div1 == div1 : false
div2 == div2 : false
Double.NaN == Double.NaN : false
Float.NaN == Float.NaN : false
它们都返回 false。
为什么 float 或 double 允许此操作(除以零)?
顺便说一句,我可以理解 float ( double )的值代表正无穷大、负无穷大、不是数字 (NaN
)...
最佳答案
简而言之,这就是 IEEE-754 标准中指定的方式,也就是 Java 的 Floating-Point Operations是基于。
The 754 model encourages robust programs. It is intended not only for numerical analysts but also for spreadsheet users, database systems, or even coffee pots. The propagation rules for NaNs and infinities allow inconsequential exceptions to vanish. Similarly, gradual underflow maintains error properties over a precision's range.
When exceptional situations need attention, they can be examined immediately via traps or at a convenient time via status flags. Traps can be used to stop a program, but unrecoverable situations are extremely rare. Simply stopping a program is not an option for embedded systems or network agents. More often, traps log diagnostic information or substitute valid results.
Flags offer both predictable control flow and speed. Their use requires the programmer be aware of exceptional conditions, but flag stickiness allows programmers to delay handling exceptional conditions until necessary.
关于java - 为什么用浮点(或 double )数字除以零不会抛出 java.lang.ArithmeticException :/by zero in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12954193/