首页 Java Java – 正负零的比较

Java – 正负零的比较

为什么 Java在比较-0.0和0.0时不一致?将数字与-0 / 0进行比较的Java标准方法是什么? 我遇到过这个特别的bugaboo: public class ZeroCompare { public static void main(String[] args) { if ( 0.0 == -0.0 ) { System.out.printl

为什么
Java在比较-0.0和0.0时不一致?将数字与-0 / 0进行比较的Java标准方法是什么?

我遇到过这个特别的bugaboo:

public class ZeroCompare {
    public static void main(String[] args) {
        if ( 0.0 == -0.0 ) {
            System.out.println("== --> same");
        } else {
            System.out.println("== --> different");
        }

        if ( new Double(0.0).equals( -0.0 ) ) {
            System.out.println("equals --> same");
        } else {
            System.out.println("equals --> different");
        }
    }
}

它打印以下内容:

== --> same
equals --> different

我非常不喜欢这样一个事实:你如何比较这两个值会影响结果,我喜欢解释.

解决方法

此行为是
actually documented:

If d1 represents +0.0 while d2 represents -0.0,or vice versa,the equal test has the value false,even though +0.0==-0.0 has the value true. This definition allows hash tables to operate properly.

本文来自网络,不代表青岛站长网立场。转载请注明出处: https://www.0532zz.com/html/kaifa/java/20200801/7604.html
上一篇
下一篇

作者: dawei

【声明】:青岛站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部