一、round()函数介绍
1.头文件#include<math.h>
2.功能只能四舍五入保留至整数
二、四舍五入,保留至整数
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
float a = 1.0/3;
float b = 2.0/3;
float c = -1.0/3;
float d = -2.0/3;
cout<<a<<"四舍五入(保留至整数):"<<round(a)<<endl; // 0
cout<<b<<"四舍五入(保留至整数):"<<round(b)<<endl; // 1
cout<<c<<"四舍五入(保留至整数):"<<round(c)<<endl; // -0
cout<<d<<"四舍五入(保留至整数):"<<round(d)<<endl; // -1
return 0;
}
三、四舍五入,保留n位小数
1.实现方法:round(float_value * pow(10, n)) * pow(10, -n)
先将待处理数据乘以10^n,然后使用round函数四舍五入,最后乘以10^(-n)。
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n;
float a = 1.0/3;
float b = 2.0/3;
float c = -1.0/3;
float d = -2.0/3;
cin>>n;
cout<<a<<"四舍五入(保留至"<<n<<"位小数):"<<round(a * pow(10, n)) * pow(10, -n)<<endl;
cout<<b<<"四舍五入(保留至"<<n<<"位小数):"<<round(b * pow(10, n)) * pow(10, -n)<<endl;
cout<<c<<"四舍五入(保留至"<<n<<"位小数):"<<round(c * pow(10, n)) * pow(10, -n)<<endl;
cout<<d<<"四舍五入(保留至"<<n<<"位小数):"<<round(d * pow(10, n)) * pow(10, -n)<<endl;
return 0;
/* 运行结果
4
0.333333四舍五入(保留至4位小数):0.3333
0.666667四舍五入(保留至4位小数):0.6667
-0.333333四舍五入(保留至4位小数):-0.3333
-0.666667四舍五入(保留至4位小数):-0.6667
*/
}