提高文本文件中字符串向量的精度

C++ Increase precision of string vector in text file

本文关键字:字符串 向量 精度 文件 高文本 文本      更新时间:2023-10-16

我正在写一个程序来读取一个文本文件,做一些计算和输出到另一个文本文件。该程序运行良好,但我的问题是,写入文本文件的数字不够精确。小数点只能到2位,我需要至少到3位。以下是我将vector<long double> new_times转换为字符串的代码,以便我可以将其写入文本文件:

//Convert vector to string
vector<string> tempStr;
for (unsigned int i(0); i < new_times.size(); ++i){
    ostringstream doubleStr;
    doubleStr << new_times[i];    
    tempStr.push_back(doubleStr.str());
}
//Write new vector to a new times file
ofstream output_file("C:/Users/jmh/Desktop/example.txt");
ostream_iterator<string> output_iterator(output_file, "n");
copy(tempStr.begin(), tempStr.end(), output_iterator);

我知道向量的精度高于小数点后2位,因为当我在cout行中使用setprecision()函数时,输出很好:

cout << setprecision(12) << new_times[3] << endl;
output: 7869.27189716

当我写入文本文件时,我可以使用setprecision()函数吗?或者我需要做点别的吗?

我可以使用setprecision()函数以某种方式当我写到文本文件?

是的,但是你必须在ostringstream上使用它来将long double打印到string

ostringstream doubleStr;
doubleStr << std::fixed << std::setprecision(12);
doubleStr << new_times[i];

将输出精度超过小数点的12位十进制数字。std::fixed是确保数字以固定格式打印;详细信息请参见文档

我建议将精度设置为numeric_limits<long double>::max_digits10,以避免在double→text→double往返过程中丢失精度。请参阅max_digits10的目的是什么以及它与digits10有何不同?对细节。

生活例子。