【问题标题】:How to read an array of doubles from file correctly?如何正确从文件中读取双精度数组?
【发布时间】:2019-10-19 14:30:23
【问题描述】:

我正在尝试从文件中读取一个数组,然后将这些值分配给另一个数组。 我得到很多零和非常大的数字。

我尝试了不同的说明符,但它们仍然相同。 当没有赋值,只打印一个数组时,就不存在这样的问题

int n;                   
FILE * fo; 
fo = fopen("f1.txt","r");
double complex mas[8];
double complex y[8];
int N = 0;
while (!feof(fo)) {
    fscanf(fo, "%lf", &mas[N]);
    printf("%lf  ", mas[N]);
    N++;
    printf("%d ", N);
}
fclose(fo);
printf("\n      N=%d\n", N);
for(n=0; n<N; n++)               
{
    y[n] = mas[n];
    printf("%f  %f\n", y[n], mas[n]);
}

看起来正在分配值,但无法打印第一个数组

【问题讨论】:

  • 检查fscanf()的返回值而不是feof()。例如while (fscanf(fo, "%lf", &amp;mas[N]) == 1) { }。此外,仅当您声明 mas[8] 时文件的浮点数不超过 8 时,此方法才有效。
  • 在打印y[n]mas[n] 时使用%lf 而不是%f。应该是printf("%lf %lf\n", y[n], mas[n]); 还要检查fopen() 的返回值。
  • @Achal %f%lfprintf 中是等价的(打印 complex 时两者都是错误的)
  • 仍然与 %lf 或 %f 相同

标签: c arrays printf double


【解决方案1】:

没有办法直接读取复数

// read a double (%lf) into a complex is wrong
fscanf(fo, "%lf", &mas[N]);

您需要单独阅读每个部分,(假设文件内容的格式为“3.14159-2.71828i”)可能与

// read a complex parts
double r, c;
if (fscanf(fo, "%lf%lfi", &r, &c) != 2) /* error */;
// join the parts
mas[N] = r + c*I;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多