是什么让以下代码打印错误? [英] What makes the following code print false?
问题描述
public class Guess {
public static void main(String[] args){
<sometype> x = <somevalue>;
System.out.println(x == x);
}
}
我必须更改sometype和somevalue以便返回假?有可能吗?
i have to change sometype and somevalue so that it returns false? is it possible?
推荐答案
一:
float x = Float.NaN;
二:
double x = 0.0/0.0;
为什么?
如前所述, NaN
永远不会等于另一个 NaN
- 请参阅 http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
As mentioned here already, NaN
is never equal to another NaN
- see http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
那么为什么这不会返回false?
So why this is not returning false?
Float x = Float.NaN;
答案是,这里有一个引用赋值,而不是原始赋值。并且在后台有一个小自动拳击。这等于:
The answer is that here, instead of a primitive assignment, there is a reference assignment. And there is a little auto boxing in the background. This is equal to:
Float x = new Float(Float.NaN);
等于:
Float x = new Float(0.0f / 0.0f);
这里x是对Float对象的引用,==运算符测试引用相等,而不是值。
Here x is a reference to a Float object, and the == operator tests reference equality, not value.
要看到此返回false,测试应该是:
To see this returning false as well, the test should have been:
x.doubleValue()==x.doubleValue();
确实返回错误
这篇关于是什么让以下代码打印错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!