如何将数字输出到文件中,所有数字都具有相同的精度

How to output numbers to a file, all of them with the same precision

本文关键字:数字 精度 数字输出 文件      更新时间:2023-10-16

我有一个双精度的二维数组,我想将这些数字输出到一个文件中(每个二维都是一行(。这不是问题。问题是,输出数字以不同的精度保存在txt文件中。示例:

0       1.173   1.3     2.0744  0       0.13

但我希望他们像:

0.0000  1.1730  1.3000  2.0744  0.0000  0.1300

我试过std::setprecision(6)std::cout.precision(6),但它们似乎不起作用,或者我用错了它们。这里是我如何将数据输出到文件的简化版本:

std::ofstream ofile("document.dat");
for(int i = 0; i < array_size; i++) {
ofile << array[i][0] << " " array[i][1] << std::endl;
}

正如注释所指出的,您希望使用std::fixed(以及设置宽度和精度(,因此您可以按照以下一般顺序获得一些东西:

#include <iostream>
#include <iomanip>
#include <vector>
int main() {
std::vector<std::vector<double>> numbers{
{1.2, 2.34, 3.456},
{4.567, 5, 6.78910}};
for (auto const &row : numbers) {
for (auto const &n : row) {
std::cout << std::setw(15) << std::setprecision(5) << std::fixed << n << "t";
}
std::cout << "n";
}
}

结果:

1.20000         2.34000         3.45600 
4.56700         5.00000         6.78910 

将浮点数与10^n相乘,并将值存储在int变量中,以去除小数。然后将整数除以10^n并将其存储在浮点中,然后就可以将其保存到一个包含n个十进制数字的文本文件中。