问:Math.round(15.5) 等于多少?Math.round(-15.5) 等于多少?
答:分别等于 16 和 -15。
因为四舍五入的原理是在参数上加 0.5 然后进行下取整。所以类似的 Math.round(15.6) 计算方式为 15.6 + 0.5 = 16.1,接着向下取整数为 16;Math.round(-15.6) 计算方式为 -15.6 + 0.5 = -15.1,接着向下取整数为 -16。
切记不是四舍五入,是加 0.5 向下取整数。
问:说说 Math.round、Math.floor、Math.ceil 区别?
答:
round 方法返回为参数值加 0.5 向下取整数。
floor 方法返回不大于参数的最大整数。
ceil 方法返回不小于参数的最小整数。
代码如下:
public class Test {
public static void main(String[] args) {
System.out.println("Math.floor(1.4)=" + Math.floor(1.4));
System.out.println("Math.floor(1.5)=" + Math.floor(1.5));
System.out.println("Math.floor(1.6)=" + Math.floor(1.6));
System.out.println("Math.floor(-1.4)=" + Math.floor(-1.4));
System.out.println("Math.floor(-1.5)=" + Math.floor(-1.5));
System.out.println("Math.floor(-1.6)=" + Math.floor(-1.6));
System.out.println("Math.floor(1)=" + Math.floor(1));
System.out.println("Math.floor(-1)=" + Math.floor(-1));
System.out.println("Math.ceil(1.4)=" + Math.ceil(1.4));
System.out.println("Math.ceil(1.5)=" + Math.ceil(1.5));
System.out.println("Math.ceil(1.6)=" + Math.ceil(1.6));
System.out.println("Math.ceil(-1.4)=" + Math.ceil(-1.4));
System.out.println("Math.ceil(-1.5)=" + Math.ceil(-1.5));
System.out.println("Math.ceil(-1.6)=" + Math.ceil(-1.6));
System.out.println("Math.ceil(1)=" + Math.ceil(1));
System.out.println("Math.ceil(-1)=" + Math.ceil(-1));
System.out.println("Math.round(1.4)=" + Math.round(1.4));
System.out.println("Math.round(1.5)=" + Math.round(1.5));
System.out.println("Math.round(1.6)=" + Math.round(1.6));
System.out.println("Math.round(-1.4)=" + Math.round(-1.4));
System.out.println("Math.round(-1.5)=" + Math.round(-1.5));
System.out.println("Math.round(-1.6)=" + Math.round(-1.6));
System.out.println("Math.round(1)=" + Math.round(1));
System.out.println("Math.round(-1)=" + Math.round(-1));
}
}
Math.floor(1.4)=1.0
Math.floor(1.5)=1.0
Math.floor(1.6)=1.0
Math.floor(-1.4)=-2.0
Math.floor(-1.5)=-2.0
Math.floor(-1.6)=-2.0
Math.floor(1)=1.0
Math.floor(-1)=-1.0
Math.ceil(1.4)=2.0
Math.ceil(1.5)=2.0
Math.ceil(1.6)=2.0
Math.ceil(-1.4)=-1.0
Math.ceil(-1.5)=-1.0
Math.ceil(-1.6)=-1.0
Math.ceil(1)=1.0
Math.ceil(-1)=-1.0
Math.round(1.4)=1
Math.round(1.5)=2
Math.round(1.6)=2
Math.round(-1.4)=-1
Math.round(-1.5)=-1
Math.round(-1.6)=-2
Math.round(1)=1
Math.round(-1)=-1
本文参考自 Java Math 类相关笔试题踩坑分析