Java 变量如何与自身不同? [英] How can a Java variable be different from itself?

查看:22
本文介绍了Java 变量如何与自身不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这个问题是否可以在 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!=xtrue.

...

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 == 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 变量如何与自身不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆