Java变量如何与自身不同? [英] How can a Java variable be different from itself?
问题描述
我想知道这个问题是否可以用Java解决(我是语言新手)。这是代码:
I am wondering if this question can be solved in Java (I'm new to the language). This is the code:
class Condition {
// you can change in the main
public static void main(String[] args) {
int x = 0;
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
}
}
我收到了以下问题:我的实验室:如何在不修改条件本身的情况下跳过第一种情况(即使 x == x
条件为假)?
I received the following question in my lab: How can you skip the first case (i.e. make the x == x
condition false) without modifying the condition itself?
推荐答案
一种简单的方法是使用 Float.NaN
:
One simple way is to use Float.NaN
:
float x = Float.NaN; // <--
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
Not ok
您可以对 Double.NaN
。
来自 JLS§15.21.1。 数字平等算子 ==
和!=
:
From JLS §15.21.1. Numerical Equality Operators ==
and !=
:
根据IEEE 754标准的规则执行浮点相等测试:
Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:
-
如果任一操作数是NaN,那么
==
的结果是false
但是!=
的结果是true
。
If either operand is NaN, then the result of
==
isfalse
but the result of!=
istrue
.
确实,测试 x!= x
是 true
当且仅当 x
的值为NaN时。
Indeed, the test x!=x
is true
if and only if the value of x
is NaN.
...
这篇关于Java变量如何与自身不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!