C/C++去小数位取整、向下取整、向上取整与四舍五入

版权声明:个人学习笔记记录 https://blog.csdn.net/Ratina/article/details/84524162

简单整理一下这四种取整处理方法~



去小数位取整 (直接截去小数点后的数据)

类型转换 (浮点型→整型)

当浮点型转换为整型时,会截去小数点之后的数据,仅保留整数位。

double x=2.3;
int y=x;
cout<<y;

输出:2

double x=-2.3;
int y=x;
cout<<y;

输出:-2




向下取整(不大于x的最大整数)

floor() 函数(包含在头文件< cmath >中)

函数原型:
double floor ( double x );
float floor ( float x );
long double floor ( long double x );

返回值: 不大于x的最大整数(但依然是浮点型)

printf("floor(%.1f) is %.1f\n",2.3,floor(2.3));
printf("floor(%.1f) is %.1f\n",2.8,floor(2.8));
printf("floor(%.1f) is %.1f\n",-2.3,floor(-2.3));

输出:
floor(2.3) is 2.0
floor(2.8) is 2.0
floor(-2.3) is -3.0




向上取整(不小于x的最小整数)

ceil() 函数(包含在头文件< cmath >中)

函数原型:
double ceil ( double x );
float ceil ( float x );
long double ceil ( long double x );

返回值: 不小于x的最小整数(但依然是浮点型)

printf("ceil(%.1f) is %.1f\n",2.3,ceil(2.3));
printf("ceil(%.1f) is %.1f\n",2.8,ceil(2.8));
printf("ceil(%.1f) is %.1f\n",-2.3,ceil(-2.3));

输出:
ceil(2.3) is 3.0
ceil(2.8) is 3.0
ceil(-2.3) is -2.0




四舍五入

①浮点数的格式化输出

控制浮点数的输出格式,会自动进行四舍五入,这里仅示范printf()

扫描二维码关注公众号,回复: 4269842 查看本文章
double pi=3.1415926printf("仅保留整数:%.f\n",pi);
printf("保留1位小数:%.1f\n",pi);
printf("保留2位小数:%.2f\n",pi);
printf("保留3位小数:%.3f\n",pi);
printf("保留4位小数:%.4f\n",pi);

输出:
仅保留整数:3
保留1位小数:3.1
保留2位小数:3.14
保留3位小数:3.142
保留4位小数:3.1416


② round() 函数(包含在头文件< cmath >中)

函数原型:
double round (double x);
float roundf (float x);
long double roundl (long double x);

返回值: x四舍五入后的整数(但依然是浮点型)

printf("round(%.1f) is %.1f\n",2.3,round(2.3));
printf("round(%.1f) is %.1f\n",2.5,round(2.5));
printf("round(%.1f) is %.1f\n",2.8,round(2.8));
printf("round(%.1f) is %.1f\n",-2.3,round(-2.3));
printf("round(%.1f) is %.1f\n",-2.8,round(-2.8));

输出:
round(2.3) is 2.0
round(2.5) is 3.0
round(2.8) is 3.0
round(-2.3) is -2.0
round(-2.8) is -3.0

若编译器不支持 round() 函数,可自行编写

double round(double x)
{
    return (x > 0.0) ? floor(x + 0.5) : ceil(x - 0.5);
}

猜你喜欢

转载自blog.csdn.net/Ratina/article/details/84524162