c - 如何从文件中正确读取 double 组?

标签 c arrays printf double

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

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

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]);
}

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

最佳答案

无法直接读取复数

// 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;

关于c - 如何从文件中正确读取 double 组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56437454/

相关文章:

c - 在 C 中打印字符串时出现无法解释的行为

Ruby sprintf 在 1.9 中发挥作用

c - 在 C 中使用 sprintf 并收到警告时出现问题

c - 这段代码中的音频是如何播放的(C/SDL)

arrays - Swift - 从字典中删除一个数组

c - 有没有不支持 ANSI C 89 的平台?

c# - 如何快速操作 byte[] 中的数据?

Java对象数组错误(卡片)

结构中的 C 变量范围

c - 注册 Windows 类 Win32