c++ 四舍五入的问题.

来源:百度知道 编辑:UC知道 时间:2024/06/02 09:02:26
在c++中
如果要把一个数四舍五入到小数点后两位要怎么做?
比如37.425→37.43

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main() {

cout <<setprecision(10) << fixed << floor(37.425 * 100 + 0.5) / 100 << endl;
return 0;
}

应该是用if 语句去判断小数点后第三位吧?个人感觉应该是这样的

printf语句不是可以吗
printf("%.2lf",fdata);

好像在C中是加上0.005.因为不附合的全舍了

程序如下:
double fun(double x)
{
int y;
y=(int)(x*1000+5)/10; //将x扩大1000倍,加5,再除10取整实现四舍五入
return (double)y/100; //还原本来的运算数
}

void main()
{
double n;
cout<<"请输入运算数:"<<endl;
cin>>n;
cout<<fun(n)<<endl;
}

函数中扩大多少倍,根据你要保留的小数位数决定~~~体会下思想