我读过关于浮点的内容,我知道NaN可能来自操作.但我无法完全理解这些概念是什么.有什么区别?
在C++编程期间可以生成哪一个?作为程序员,我可以编写一个程序来导致sNaN吗?
以下陈述java.lang.ArithmeticException: / by zero
显而易见.
System.out.println(0/0);
Run Code Online (Sandbox Code Playgroud)
因为文字0
被认为是int
文字并且在整数算术中不允许除以零.
但是,以下情况不会抛出任何异常java.lang.ArithmeticException: / by zero
.
int a = 0;
double b = 6.199;
System.out.println((b/a));
Run Code Online (Sandbox Code Playgroud)
它显示Infinity
.
以下语句生成NaN
(非数字),没有例外.
System.out.println(0D/0); //or 0.0/0, or 0.0/0.0 or 0/0.0 - floating point arithmetic.
Run Code Online (Sandbox Code Playgroud)
在这种情况下,两个操作数都被认为是双精度数.
同样,以下语句不会抛出任何异常.
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 …
Run Code Online (Sandbox Code Playgroud) 为什么这段代码不会抛出ArithmeticException
?看一看:
public class NewClass {
public static void main(String[] args) {
// TODO code application logic here
double tab[] = {1.2, 3.4, 0.0, 5.6};
try {
for (int i = 0; i < tab.length; i++) {
tab[i] = 1.0 / tab[i];
}
} catch (ArithmeticException ae) {
System.out.println("ArithmeticException occured!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道!
RuntimeException
对于导致分配的任何代码,我想有一些项目范围的失败快速机制(可能是a )NaN
.
在我的项目NaN
中永远不是一个有效的价值.
我意识到我可以添加断言(使用isNaN)或其他测试,但我想知道是否有更优雅的方式.
看过Double.java的源代码和一些常量就好
/**
* Constant for the Not-a-Number (NaN) value of the {@code double} type.
*/
public static final double NaN = 0.0 / 0.0;
/**
* Constant for the positive infinity value of the {@code double} type.
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* Constant for the negative infinity value of the {@code double} type.
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
Run Code Online (Sandbox Code Playgroud)
但我想知道它为什么不抛出ArithmeticException(除以零)?
我试过了
public static final int VALUE = 0/0;
Run Code Online (Sandbox Code Playgroud)
现在它正在抛出异常,但是当我说 …