Java 常用数学方法

Java  Match.round()方法 表示的是四舍五入。它是Java面试题之一

四舍五入的原则是 去掉符号位,只考虑有效的位数和数值。

  • 对于正数,大于等于0.5都向上进取一位,如Math.round(1.5)等于2
  • 对于负数,大于等于0.6都向上进取一位,如Math.round(-1.6)等于-2,Math.round(-1.5)等于-1。
或者在参数上加0.5然后进行下取整,两种处理方式的原理都可以得到我们要的结果。

语法

它有两种类型的语法,可以传不同类型的参数,语法如下:
int Math.round(double d)
int Math.round(float f) 

参数

  • d: double类型的参数
  • f:float类型的参数

返回值

返回一个int类型的整数。

例子

public class MathRoundExample{
    public static void main(String[] args) {
        System.out.println(Math.round(-1.2));
        System.out.println(Math.round(-1.5));
        System.out.println(Math.round(-1.6));

        System.out.println(Math.round(1.2));
        System.out.println(Math.round(1.5));
        System.out.println(Math.round(1.6));

    }
}

输出:

-1
-1
-2
1
2
2