001-取整函数(ceil、floor、round)

取整函数主要有三种:ceil()、floor()、round()

1. ceil() 向上取整

函数名: ceil
用 法: double ceil(double x);
功 能: 返回大于或者等于指定表达式的最小整数。
头文件:math.h
返回数据类型:double

package com.test;

public class CeilTest {

    private static final double[] TEST_DATA = {1, 1.3, 1.6, 0, -1, -1.3, -1.6 };

    public static void main(String[] args) {
        for(double num : TEST_DATA){
            test(num);
        }
    }

    public static void test(double num){
        System.out.println(num+"的Math.ceil结果:"+Math.ceil(num));
    }
}

在这里插入图片描述
向上取整的时候,正数,则直接将当前整数加一;
负数,则将整数后面的数据抹除;
整数,则不变。

2. floor() 向下取整

说明
在C语言的库函数中,floor函数的语法如下:
#include <math.h>
double floor( double arg );
功能: 函数返回不大于arg的最大整数值。

#include <math.h>
#include <stdio.h>
int main(void) {
    printf("floor(+2.7) = %+.1f\n", floor(2.7));
    printf("floor(-2.7) = %+.1f\n", floor(-2.7));
    printf("floor(-0.0) = %+.1f\n", floor(-0.0));
    printf("floor(-Inf) = %+f\n",   floor(-INFINITY));
}
//程序执行结果
floor(+2.7) = +2.0
floor(-2.7) = -3.0
floor(-0.0) = -0.0
floor(-Inf) = -inf
package com.test;

public class CeilTest {

    private static final double[] TEST_DATA = {1, 1.3, 1.6, 0, -1, -1.3, -1.6 };

    public static void main(String[] args) {
        for(double num : TEST_DATA){
            test(num);
        }
    }
    public static void test(double num){
        System.out.println(num+"的Math.floor结果:"+Math.floor(num));
    }
}

在这里插入图片描述

3. round() 四舍五入

Round函数返回一个数值,该数值是按照指定的小数位数进行四舍五入运算的结果。

语法
round(number,digits)
参数
number,要四舍五入的数,digits是要小数点后保留的位数

如果 digits 大于 0,则四舍五入到指定的小数位。
如果 digits 等于 0,则四舍五入到最接近的整数。
如果 digits 小于 0,则在小数点左侧进行四舍五入。
如果round函数只有参数number,等同于digits 等于 0。

返回值
四舍五入后的值

=ROUND(3.19, 1) 将 3.19 四舍五入到一个小数位 (3.2)
=ROUND(2.649, 1) 将 2.649 四舍五入到一个小数位 (2.6)
=ROUND(-5.574, 2) 将 -5.574 四舍五入到两小数位 (-5.57)
=ROUND(18.8, -1) 将 18.8 四舍五入到小数点左侧一位 (20)。这个参数-1表示取整到十位数。

package com.test;

public class CeilTest {

    private static final double[] TEST_DATA = {1, 1.3, 1.6, 0, -1, -1.3, -1.6 };

    public static void main(String[] args) {
        for(double num : TEST_DATA){
            test(num);
        }
    }
    public static void test(double num){
        System.out.println(num+"的Math.round结果:"+Math.round(num));
    }
}

在这里插入图片描述

4.拓展

Roundup函数
Rounddown函数

  • 3
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值