【面试题】Math 的 floor,round 和 ceil 方法比较

本文详细解析了数学函数ceil(), floor(), rint(), round()的定义与用法,通过代码示例展示了这些函数在处理不同数值时的行为,是理解并运用这些基本数学操作的重要资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、定义

1ceil()  “天花板”,向上取最接近的整数。
返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。
2floor() “地板”,向下取最接近的整数。
返回小于等于(<=)给定参数的最大整数 。
3rint()  
返回与参数最接近的整数。返回类型为double。注:如果上下都接近,取偶数。
4round()
它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。

二、代码示例

    public static void main(String[] args) {
        double[] nums = {1.4, 1.5, 1.6, -1.4, -1.5, -1.6};
        for(double num:nums){
            test(num);
        }
    }

    private static void test(double num) {
        System.out.println("Math.floor("+num+")="+Math.floor(num));
        System.out.println("Math.round("+num+")="+Math.round(num));
        System.out.println("Math.ceil("+num+")="+Math.ceil(num));
        System.out.println("Math.rint("+num+")="+Math.rint(num));
    }
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.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.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.rint(1.4)=1.0
Math.rint(1.5)=2.0(!!)
Math.rint(1.6)=2.0
Math.rint(-1.4)=-1.0
Math.rint(-1.5)=-2.0(!!)
Math.rint(-1.6)=-2.0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值