gpt4 book ai didi

c - 将 .dat 文件中的 double float 存储到一维数组中

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:54 24 4
gpt4 key购买 nike

所以我在从 .dat 文件中存储一些数字时遇到了一些困难。文件如下:

1
2
7
10
9
4
0
5
6
8
3

我必须尝试检索此信息的代码是:

#include <stdio.h>
#include <stdlib.h>

#define N 11

int main(int argc, char** argv) {

//Declare variables: number of elements, counter, array, & valuesto
//print
int i;
double a[N], num, temp;
FILE* dat;

//Print space for program cleanliness
printf("\n");

//Open file
dat = fopen("zero.dat", "r");

//Initialize i
i=0;

//Read in infromation from file
while(!feof(dat) && i < N){
printf("This is loop number %d\n", i);
num = fscanf(dat,"%lf", &temp);
printf("Temp variable is stored as: %f\n", temp);
printf("Number of characters read in: %d\n\n", num);
a[i] = temp;
i++;
}

fclose(dat);

for(int j=0;j<i;j++){

printf("%f\n", a[j]);

}

//Exit program
exit(EXIT_SUCCESS);
}
/**************************************************************************/

输出是:

This is loop number 0
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 1
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 2
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 3
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 4
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 5
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 6
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 7
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 8
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 9
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

This is loop number 10
Temp variable is stored as: 0.000000
Number of characters read in: 1541763072

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

此外,需要注意的是,我使用的是 NetBeans IDE 8.0.2; zero.dat 文件位于与源相同的项目文件夹中。

最佳答案

您的代码打印 Number of characters read in: 1541763072 因为 fscanf 返回一个 int 并且您将其收集在一个 double 变量中,不确定为什么放置垃圾值但是把它改成像这样的 int 变量

int j;
j=fscanf(dat,"%lf", &temp);
printf("Number of characters read in: %d\n\n", j);

检查文件是否存在是一个很好的编程习惯。如果文件不存在,你只会得到一个段错误,你不会知道为什么它会返回一个段错误。而是处理它

dat = fopen("zero.dat", "r");
if(dat == NULL)
{
//your message
return;
}

关于c - 将 .dat 文件中的 double float 存储到一维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34060864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com