Java 变量如何与自身不同? [英] How can a Java variable be different from itself?
问题描述
我想知道这个问题是否可以在 Java 中解决(我是该语言的新手).这是代码:
class 条件 {//你可以在main中改变公共静态无效主(字符串 [] args){整数 x = 0;如果(x == x){System.out.println("确定");} 别的 {System.out.println("不行");}}}
我在实验室中收到以下问题:如何在不修改条件本身的情况下跳过第一种情况(即,使 x == x
条件为假)?
一种简单的方法是使用 Float.NaN
:
float x = Float.NaN;//<--如果(x == x){System.out.println(确定");} 别的 {System.out.println("不行");}
<前>不好
您可以使用 Double.NaN
.
来自JLS §15.21.1. 数值相等运算符 ==
和 !=
:
浮点相等性测试按照IEEE 754标准的规则进行:
如果任一操作数为 NaN,则
==
的结果为false
但!=
的结果为true
.确实,当且仅当
x
的值为 NaN 时,测试x!=x
是true
.
...
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");
}
}
}
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?
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
You can do the same with Double.NaN
.
From JLS §15.21.1. Numerical Equality Operators ==
and !=
:
Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:
If either operand is NaN, then the result of
==
isfalse
but the result of!=
istrue
.Indeed, the test
x!=x
istrue
if and only if the value ofx
is NaN....
这篇关于Java 变量如何与自身不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!