public class Test {
public static void main(String[] args) {
// floor 向下取整 即取不大于原值的最大整数
System.out.println("Math.floor(10.5)=" + Math.floor(10.5));
System.out.println("Math.floor(10.7)=" + Math.floor(10.7));
System.out.println("Math.floor(10.1)=" + Math.floor(10.1));
System.out.println("Math.floor(-10.5)=" + Math.floor(-10.5));
System.out.println("Math.floor(-10.7)=" + Math.floor(-10.7));
System.out.println("Math.floor(-10.1)=" + Math.floor(-10.1));
System.out.println();
// ceil 向上取整 即不小于原值的最小整数
System.out.println("Math.ceil(10.5)=" + Math.ceil(10.5));
System.out.println("Math.ceil(10.7)=" + Math.ceil(10.7));
System.out.println("Math.ceil(10.1)=" + Math.ceil(10.1));
System.out.println("Math.ceil(-10.5)=" + Math.ceil(-10.5));
System.out.println("Math.ceil(-10.7)=" + Math.ceil(-10.7));
System.out.println("Math.ceil(-10.1)=" + Math.ceil(-10.1));
System.out.println();
// round 保持符号不变,绝对值四舍五入
System.out.println("Math.round(10.5)=" + Math.round(10.5));
System.out.println("Math.round(10.7)=" + Math.round(10.7));
System.out.println("Math.round(10.1)=" + Math.round(10.1));
System.out.println("Math.round(-10.5)=" + Math.round(-10.5));
System.out.println("Math.round(-10.7)=" + Math.round(-10.7));
System.out.println("Math.round(-10.1)=" + Math.round(-10.1));
System.out.println();
}
}
运行结果
Math.floor(10.5)=10.0
Math.floor(10.7)=10.0
Math.floor(10.1)=10.0
Math.floor(-10.5)=-11.0
Math.floor(-10.7)=-11.0
Math.floor(-10.1)=-11.0
Math.ceil(10.5)=11.0
Math.ceil(10.7)=11.0
Math.ceil(10.1)=11.0
Math.ceil(-10.5)=-10.0
Math.ceil(-10.7)=-10.0
Math.ceil(-10.1)=-10.0
Math.round(10.5)=11
Math.round(10.7)=11
Math.round(10.1)=10
Math.round(-10.5)=-10
Math.round(-10.7)=-11
Math.round(-10.1)=-10
所谓向上向下,相当于是构建了这样一个数轴,沿箭头方向数值增大:

本文详细介绍了Java中使用Math类进行的几种常见数学运算方法,包括向下取整(floor)、向上取整(ceil)以及四舍五入(round)的实现方式,并通过示例代码展示了不同方法在正负数上的应用效果。
4261

被折叠的 条评论
为什么被折叠?



