简单整理一下这四种取整处理方法~
去小数位取整 (直接截去小数点后的数据)
类型转换 (浮点型→整型)
当浮点型转换为整型时,会截去小数点之后的数据,仅保留整数位。
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
四舍五入
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);
}