提高文本文件中字符串向量的精度
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()
函数吗?或者我需要做点别的吗?
我可以使用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有何不同?对细节。
生活例子。
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值