我刚才有一个我无法回答的问题.
假设您在Java中使用此循环定义:
while (i == i) ;
Run Code Online (Sandbox Code Playgroud)
如果循环不是无限循环并且程序只使用一个线程i,i那么类型和值是什么?
Zac*_*ena 125
double i = Double.NaN;
Run Code Online (Sandbox Code Playgroud)
Double.equals()的API解释了答案:"Double.NaN == Double.NaN的值为false".这在Java语言规范" 浮点类型,格式和值 "下详细说明:
NaN是无序的,所以数值比较运算<,<=,>,和>=返回false如果任一或两个操作数都NaN.等于运算符==将返回false如果操作数是NaN和不平等操作!=返回true如果操作数是NaN.尤其x!=x是true当且仅当x是NaN,和(x<y) == !(x>=y)将是false,如果x和y是NaN.
float i = Float.NaN;
while(i == i) ;
System.out.println("Not infinite!");
Run Code Online (Sandbox Code Playgroud)
由于其他人说它是NaN,我对官方(JDK 6)的实施感到好奇Double.isNaN,并且看到:
/**
* Returns <code>true</code> if the specified number is a
* Not-a-Number (NaN) value, <code>false</code> otherwise.
*
* @param v the value to be tested.
* @return <code>true</code> if the value of the argument is NaN;
* <code>false</code> otherwise.
*/
static public boolean isNaN(double v) {
return (v != v);
}
Run Code Online (Sandbox Code Playgroud)