栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

取整函数(ceil、floor、round)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

取整函数(ceil、floor、round)

取整函数(ceil、floor、round)
  • 1. ceil() 向上取整
  • 2. floor() 向下取整
  • 3. round() 四舍五入
  • 4.拓展

取整函数主要有三种: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
double floor( double arg );
功能: 函数返回不大于arg的最大整数值。

#include 
#include 
int main(void) {
    printf("floor(+2.7) = %+.1fn", floor(2.7));
    printf("floor(-2.7) = %+.1fn", floor(-2.7));
    printf("floor(-0.0) = %+.1fn", floor(-0.0));
    printf("floor(-Inf) = %+fn",   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函数

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号