加入收藏 | 设为首页 | 会员中心 | 我要投稿 莱芜站长网 (https://www.0634zz.com/)- 云连接、建站、智能边缘云、设备管理、大数据!
当前位置: 首页 > 编程开发 > Java > 正文

Java – 正负零的比较

发布时间:2020-08-01 08:27:58 所属栏目: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.

(编辑:莱芜站长网)

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

    推荐文章
      热点阅读