java的math常用方法

鉴于java求整时欲生欲死,整理常用math如下:

1: java取整

     a:floor向下取整

       用法:Math.floor(num)

       Math.floor(1.9)//1                      Math.floor(-1.9)//-2

    b:  round四舍五入

      用法:Math.round(num)实际上是等价于Math.floor(num+0.5)

      Math.round(1.5)//2                     Math.round(1.4)//1

      Math.round(-1.4)//-1                  Math.round(-1.5)//-1               Math.round(-1.6)//-2

    c:  ceil取不小于num的最小整数

       用法: Math.ceil(num)

       Math.ceil(1.4)//2      Math.ceil(1.5)//2             Math.ceil(1.6)//2

       Math.ceil(-1.4)//-1   Math.ceil(-1.5)//-1           Math.ceil(-1.6)//-1

    d:  神级方法直接加(int)强制转换,直接去掉小数点位,没有任何向上向下,需要时最好用的方法

2: java求绝对值

     Math.abs(num)

     Math.abs(-30.5)//30.5

3:   java随机数

     Math.random()随机去0~1的数

     (int)(100*Math.random())这样就可以取0~100随机整数

4: java幂函数

     Math.pow(a,b)a的b次方

     Math.pow(x,2)就是平方

     Math.pow(x,3)就是立方

5: java开根号

     Math.sqrt(num)num的平方根

原文地址:https://www.cnblogs.com/fireyjy/p/4720929.html