取整函数ceil() : floor() : round() (C++)

1.ceil()函数

 A. 函数原型:头文件:‘cmath’
在这里插入图片描述
 C. 介绍:
  将 x 四舍五入向上取整,取大于等于 x 的最小整数
 D. 代码:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    
    
    printf("ceil of 2.5 is %.1lf\n", ceil(2.5)); // 3.0
    printf("ceil of 2.3 is %.1lf\n", ceil(2.3)); // 3.0
    printf("ceil of 0 is %.1lf\n", ceil(0.0)); // 0.0
    printf("ceil of -2.5 is %.1lf\n", ceil(-2.5)); // -2.0
}

2.floor()函数

 A. 函数原型:头文件:‘cmath’
在这里插入图片描述
 C. 介绍:
  将 x 向下取整,取小于等于 x 的最大整数
 D. 代码:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    
    
    printf("floor of 2.5 is %.1lf\n", floor(2.5)); // 2.0
    printf("floor of 2.0 is %.1lf\n", floor(2.3)); // 2.0
    printf("floor of 0 is %.1lf\n", floor(0.0)); // 0.0
    printf("floor of -2.5 is %.1lf\n", floor(-2.5)); // -3.0
}

3.round()函数

 A. 函数原型:头文件:‘cmath’
在这里插入图片描述

 C. 介绍:
  取离 x 距离更近的整数。假如距离是一样近的,则向远离0的方向取整
 D. 代码:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    
    
    printf("round of 2.5 is %.1lf\n", round(2.5)); // 3.0
    printf("round of 2.3 is %.1lf\n", round(2.3)); // 2.0
    printf("round of 0 is %.1lf\n", round(0.0)); // 0.0
    printf("round of -2.5 is %.1lf\n", round(-2.5)); // -3.0
}

猜你喜欢

转载自blog.csdn.net/weixin_51566349/article/details/130352657