您的位置:首页 > 其它

double类型变量输出到文本文件(txt) 控制输出有效位数

2017-03-28 09:48 267 查看
在C++中将double变量输出到txt文本中时,使用默认的输出操作符输出,只能输出6位有效数字,有时不能达到精度要求。没有精度控制,将double变量输出到txt的代码如下

#include <fstream>
using namespace std;
int main()
{
double  variable = 1.0 / 3;
ofstream   myfile("double.txt");
myfile << variable;
myfile.close();
return 0;
}


txt中输出结果为: 0.333333,六位有效数字

可以通过std::setprecision( )函数来控制输出精度,使用该函数需要添加头文件。

#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
double  variable = 1.0 / 3;
ofstream   myfile("double.txt");
myfile <<  std::setprecision(10) << variable;
myfile.close();
return 0;
}


txt中输出结果为: 0.3333333333,十位有效数字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息