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

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

  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值