ARTICLE

【随手记】C++中的取整:ceil、floor与round

技术博客随手记timeStarry约 203 字预计阅读 1 分钟

在大多数编程语言中,默认取整方式为截断取整,而在数学运算中,我们经常需要使用其它取整方式。在C++ cmath中包含了这三类取整函数:向上取整ceil(),向下取整floor()和四舍五入round()。

向上取整 ceil()

函数原型:double ceil(doube x) 输入一个浮点值,返回其向上取整结果,默认为一个有六位小数的double值

例:

C++
    int i = ceil(2.2);
    int j = ceil(-2.2);

    printf("The ceil of 2.2 is %d\n", i);
    printf("The ceil of -2.2 is %d\n", j);
    return 0;

输出结果为

纯文本
The ceil of 2.2 is 3
The ceil of 2.2 is -2

向下取整 floor()

函数原型:double floor(doube x) 输入一个浮点值,返回其向下取整结果,默认为一个有六位小数的double值

例:

C++
    int i = floor(2.2);
    int j = floor(-2.2);

    printf("The floor of 2.2 is %d\n", i);
    printf("The floor of -2.2 is %d\n", j);
    return 0;

输出结果为

纯文本
The floor of 2.2 is 2
The floor of -2.2 is -3

四舍五入 round()

函数原型:double floor(doube x) 输入一个浮点值,对其进行四舍五入,默认返回值为double类型

C++
    int i = round(2.2);
    int j = round(2.7);

    printf("The round of 2.2 is %d\n", i);
    printf("The round of 2.7 is %d\n", j);
    return 0;

输出结果为

纯文本
The round of 2.2 is 2
The round of 2.7 is 3

参考阅读:https://blog.csdn.net/dangzhangjing97/article/details/81279862

COMMENTS00 条

评论

还没有评论

可以在下面留下第一条。昵称和内容会公开显示。

发表评论

评论审核后公开。邮箱始终私有,提交时记录的 IP 地址只有作者可见,180 天后清除。当前不发送回复通知。