思路:
当需要保留有效位的位数一定的时候,就需要对后续的数据进行处理,例如①四舍五入;②截断;这时我们可以通过三个函数来进行处理:①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