zoukankan      html  css  js  c++  java
  • 解读Java中BigDecimal.ZERO.compareTo()的返回值含义

    Java compareTo() 用法

    例如:

    public static void main(String[] args) {
        BigDecimal bnum1, bnum2;

        bnum1 = new BigDecimal("10");
        bnum2 = new BigDecimal("20");

        int res = bnum1.compareTo(bnum2); 

        String str1 = "两个数相等";
        String str2 = "第一个数更大";
        String str3 = "第二个数更大";

        if( res == 0 )
            System.out.println( str1 );
        else if( res == 1 )
            System.out.println( str2 );
        else if( res == -1 )
            System.out.println( str3 );
        }
    }
    运行代码,得到以下结果:
    第二个数更大

    为什么比较返回值是0,-1和1呢? 我们去看看源代码!

    根据源码中的三元运算符

    可以发现:

    情况1. 如果xs等于ys,则返回0。

    情况2. 如果xs不等于ys,则会执行另外一个三元运算符((xs > ys) ? 1 : -1)

    这时候就会比较 xs 和 ys:

     xs > ys 返回 1,

    xs < ys 返回 -1。

    因此得到结论!

    两个数比较的返回值

    • 如果第一个参数与第二个参数相等返回0。

    • 如果第一个参数小于第二个参数返回 -1。

    • 如果第一个参数大于第二个参数返回 1。

  • 相关阅读:
    python 3 dict函数 神奇的参数规则
    python 3 黑色魔法元类初探
    私有变量为何传给了子类?
    [转]django-registration quickstart
    DoesNotExist at /account/
    DoesNotExist at /admin/
    setting.py
    Python excel 奇怪的通信规则
    Python 一个奇特的引用设定
    Chrome 内存和CPU消耗量双料冠军
  • 原文地址:https://www.cnblogs.com/jpfss/p/10186132.html
Copyright © 2011-2022 走看看