做题时经常需要截断小数点,向上取整或者向下取整,以前使用printf("%.2f",n);进行截断操作,但如果数据不需要输出,这种做法就行不通了,此时可以使用floor函数向下取整或者ceil函数向上取整。
头文件:#include<cmath>
一.floor() 函数(向下取整)
1、函数原型:
double floor ( double x );
float floor ( float x );
long double floor ( long double x );
2、功能:返回一个小于传入参数的最大整数
3、参数:x为将来被处理的数
4、返回值:返回不大于x的最大整数
5、注在C语言中只有double一个原型
6、示例程序
#include <cstdio>
#include <cmath>
int main ()
{
printf ("floor of 2.3 is %.1lf/n", floor (2.3) );
printf ("floor of 2.6 is %.1lf/n", floor (2.6) );
printf ("floor of -2.3 is %.1lf/n", floor (-2.3) );
printf ("floor of -2.6 is %.1lf/n", floor (-2.6) );
return 0;
}
输出:
floor of 2.3 is 2.0
floor of 2.6 is 2.0
floor of -2.3 is -3.0
floor of -2.6 is -3.0
二.ceil()函数(向上取整)
1、函数原型:
double ceil ( double x );
float ceil ( float x );
long double ceil ( long double x );
2、功能:返回一个大于传入参数的最小整数
3、参数:x为将来被处理的数
4、返回值:返回不小于x的最小整数
5、注在C语言中只有double一个原型
6、示例程序
#include <cstdio>
#include <cmath>
int main ()
{
printf ("ceil of 2.3 is %.1lf/n", ceil (2.3) );
printf ("ceil of 2.6 is %.1lf/n", ceil (2.6) );
printf ("ceil of -2.3 is %.1lf/n", ceil (-2.3) );
printf ("ceil of -2.6 is %.1lf/n", ceil (-2.6) );
return 0;
}
输出:
ceil of 2.3 is 3.0
ceil of 2.6 is 3.0
ceil of -2.3 is -2.0
ceil of -2.6 is -2.0
三.round()函数 (四舍五入)
C++中没有round函数,需要自己建立(或者直接用floor函数和ceil函数模拟)。
示例程序:
#include <cstdio>
#include <cmath>
double round(double r){
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
int main ()
{
printf ("round of 2.3 is %.1lf/n", round (2.3) );
printf ("round of 2.6 is %.1lf/n", round (2.6) );
printf ("round of -2.3 is %.1lf/n", round (-2.3) );
printf ("round of -2.6 is %.1lf/n", round (-2.6) );
return 0;
}
示例程序输出:
round of 2.3 is 2.0
round of 2.6 is 3.0
round of -2.3 is -2.0
round of -2.6 is -3.0