Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将数字输出到一个文件中,所有数字都具有相同的精度_C++_File_Precision_Iostream - Fatal编程技术网

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

C++ 如何将数字输出到一个文件中,所有数字都具有相同的精度,c++,file,precision,iostream,C++,File,Precision,Iostream,我有一个二维的双精度数组,我想把这些数字输出到一个文件中(每个第二维是一行)。这不是问题。问题是输出的数字以不同的精度保存在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),但它们似乎不起作用,或者可能我用错了它们。这里是我如何

我有一个二维的双精度数组,我想把这些数字输出到一个文件中(每个第二维是一行)。这不是问题。问题是输出的数字以不同的精度保存在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::文件流(“document.dat”);
for(int i=0;iofile将浮点数乘以10^n,并将值存储在一个int变量中以去除小数。然后将整数除以10^n,并将其存储在浮点数中,然后就可以将其保存到一个文本文件中,该文件的小数位数为n。

如注释所述,您希望使用
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";
    }
}

您是否记得使用
std::fixed
以及
setprecision
    1.20000         2.34000         3.45600 
    4.56700         5.00000         6.78910