C++学习之floor函数,ceil函数和round函数

非 Y 不嫁゛ 提交于 2019-12-02 23:15:04

    做题时经常需要截断小数点,向上取整或者向下取整,以前使用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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!