C++ 提高文本文件中字符串向量的精度
C++ Increase precision of string vector in text file
我正在编写一个程序来读取一个文本文件,进行一些计算并输出到另一个文本文件中。该程序运行良好,但我遇到的问题是写入文本文件的数字不够精确。它们只保留 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()
函数吗?或者我需要做其他事情吗?任何帮助将不胜感激。
Can I use the setprecision() function somehow when I am writing to the text file?
是的,但是您必须在 ostringstream
上使用它来将 long double
打印到 string
。
ostringstream doubleStr;
doubleStr << std::fixed << std::setprecision(12);
doubleStr << new_times[i];
将打印小数点后 12 位小数精度的数字。 std::fixed
是为了确保数字以固定格式打印;有关详细信息,请参阅 the documentation。
我建议将精度设置为 numeric_limits<long double>::max_digits10
以避免在 double → text → double 往返过程中丢失精度。有关详细信息,请参阅 What is the purpose of max_digits10 and how is it different from digits10?。
我正在编写一个程序来读取一个文本文件,进行一些计算并输出到另一个文本文件中。该程序运行良好,但我遇到的问题是写入文本文件的数字不够精确。它们只保留 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()
函数吗?或者我需要做其他事情吗?任何帮助将不胜感激。
Can I use the setprecision() function somehow when I am writing to the text file?
是的,但是您必须在 ostringstream
上使用它来将 long double
打印到 string
。
ostringstream doubleStr;
doubleStr << std::fixed << std::setprecision(12);
doubleStr << new_times[i];
将打印小数点后 12 位小数精度的数字。 std::fixed
是为了确保数字以固定格式打印;有关详细信息,请参阅 the documentation。
我建议将精度设置为 numeric_limits<long double>::max_digits10
以避免在 double → text → double 往返过程中丢失精度。有关详细信息,请参阅 What is the purpose of max_digits10 and how is it different from digits10?。