gpt4 book ai didi

java - Java 变量如何与自身不同?

转载 作者:IT老高 更新时间:2023-10-28 11:48:38 25 4
gpt4 key购买 nike

我想知道这个问题是否可以用 Java 解决(我是该语言的新手)。这是代码:

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 条件为假)?

最佳答案

一种简单的方法是使用 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. 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 == is false but the result of != is true.

    Indeed, the test x!=x is true if and only if the value of x is NaN.

...

关于java - Java 变量如何与自身不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20374825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com