C++算法:四舍五入和截断

思路:

        当需要保留有效位的位数一定的时候,就需要对后续的数据进行处理,例如①四舍五入;②截断;这时我们可以通过三个函数来进行处理:①round;②floor;③ceil;这三个函数都位于include<math.h>头文件中。

1、round(number):指将小数点后的数据进行四舍五入;

2、floor(number):指将小数点后的数据进行向下取整,即取不大于number的最大整数;

3、ceil(number):指将小数点后的数据进行向上取整,即取大于number的最小整数;

核心代码:

cout<<round(A)<<round(B)<<round(C)<<endl;

cout<<floor(A)<<floor(B)<<floor(C)<<endl;

cout<<ceil(A)<<ceil(B)<<ceil(C)<<endl;

完整代码:

//四舍五入和截断
#include<iostream>
#include<math.h>
using namespace std;

//手写round函数
int round(double number)
{
	return (int)(number + 0.5);
}

int main()
{
	double A,B,C;    //设置三个变量用于测试
	cin>>A>>B>>C;
	//round函数(实现四舍五入)
	cout<<"round():"<<endl;
	cout<<"A:"<<round(A)<<'\t'<<"B:"<<round(B)<<'\t'<<"C:"<<round(C)<<endl;

	//floor()函数(向下取整:不大于x的最大整数)
	cout<<"floor():"<<endl;
	cout<<"A:"<<floor(A)<<'\t'<<"B:"<<floor(B)<<'\t'<<"C:"<<floor(C)<<endl;

	//ceil()函数(向上取整:大于x的最小整数)
	cout<<"ceil():"<<endl;
	cout<<"A:"<<ceil(A)<<'\t'<<"B:"<<ceil(B)<<'\t'<<"C:"<<ceil(C)<<endl;

	system("pause");
	return 0;
}

输入:

2.3
5.8
1.5

输出:

round():
A:2     B:6     C:2
floor():
A:2     B:5     C:1
ceil():
A:3     B:6     C:2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值