加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java – 正负零的比较

发布时间:2020-12-14 16:29:25 所属栏目: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.println("== -- same"); } else
为什么 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读