Java Math的floor、ceil、round方法

这几个方法都位于java.lang包下的Math类中,都为静态方法。

ceil方法:

static double ceil(double a)

返回值为double类型,返回的值大于或等于参数的double类型的值,并且等于某个整数(这么说总感觉怪怪的)

floor方法:

static double floor(double a)

返回值同样为double类型,返回的值为小于或等于参数的double类型的值,并且等于某个整数

round方法:

    //该方法为重载方法
    static long round(double a)
    static int round(float a)

返回最接近参数的整数,该方法等同于Math.floor(a + 0.5)并将结果转换为long或int类型

public class MathTest {
    public static void main(String[] args) {
        double[] nums = {-0.6, -1.5, -1, 0.5, 1.2, 1.8};
        for(double n : nums) {
            test(n);
        }
    }

    public static void test(double a) {
        System.out.println("Math.ceil(" + a + ")=" + Math.ceil(a));
        System.out.println("Math.floor(" + a + ")=" + Math.floor(a));
        System.out.println("Math.round(" + a + ")=" + Math.round(a));
    }
}

运行结果:

Math.ceil(-0.6)=-0.0
Math.floor(-0.6)=-1.0
Math.round(-0.6)=-1
Math.ceil(-1.5)=-1.0
Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.0)=-1.0
Math.floor(-1.0)=-1.0
Math.round(-1.0)=-1
Math.ceil(0.5)=1.0
Math.floor(0.5)=0.0
Math.round(0.5)=1
Math.ceil(1.2)=2.0
Math.floor(1.2)=1.0
Math.round(1.2)=1
Math.ceil(1.8)=2.0
Math.floor(1.8)=1.0
Math.round(1.8)=2

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值