以 18 位以上的精度将 CSV 读入 C 中的网格

Reading a CSV into a grid in C with 18+ digits of precision

我有一个名为 "Q.csv" 的文件,它是一个包含以下内容的文本文件:

-4.999118817962964961e-07 1.500000000000000197e-08 9.151794806638024753e-08 9.151794806638024753e-08

我想将其作为 2x2 矩阵读入 C 程序。目前我的程序是这样的。

 #include <stdio.h>
 #include <stdlib.h>
 int main(){
    FILE* inf;
    inf = fopen("Q.csv","r");
    int nrows = 2;
    int ncols = 2;
    double grid[nrows][ncols];
    double t;
    size_t x, y;
        for (x=0; x<ncols; ++x){
                for(y=0; y< nrows; ++y){
                        fscanf(inf,"%lg ",&t);
                        grid[x][y]=t;
                        printf("%lg\n",grid[x][y]);
                }
        }
        fclose(inf);
}

这个程序有效。但它并没有输出最初在 Q.csv 中的所有精度 - 例如,它输出第一个数字为 -4.99912e-07。例如,如果我拿走 %lg 并将其更改为 %.18g,它会输出错误的内容。如果我放 %.18lg 也一样。事实上,这两个结果都导致神秘数字 4.94065645841246544e-324 重复(这是从哪里来的?!)

如何才能将文件中的所有精度转换为 C?

将使用 fscanf(inf,"%lg ",&t); 尽可能地读取输入。

要打印出小数点后 18 位数字,请使用

 printf("%.*le\n",18, grid[x][y]);

如果 double 有足够的精度,检查值 DBL_DIG 必须至少为 10。我怀疑 double 只适用于 15-17 位总数字。


要获得 所有 精度,请参阅 Printf width specifier to maintain precision of floating-point value