我正在尝试加载一个数组,并打印数组中的项目(array_num)以及数组中0位的值。我的代码工作得不好,我想知道为什么。任何帮助将不胜感激。输入文件是:
-1.000000
0.250000
-1.333333
0.484375
1.958333
3.119792
4.000000
4.630208
5.041667
5.265625
5.333333
5.276042
5.125000
4.911458
4.666667
4.421875
4.208333
4.057292
4.000000
4.067708
4.291667
4.703125
5.333333
6.213542
7.375000
8.848958
10.666667
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
//start of main code
int main(void)
{
//declare variables
float x1, h;
int i, array_num;
float diff_arr[50];
FILE*indiff;
indiff = fopen("indiff.txt","r");
if (indiff == NULL)
printf("Error Opening File...\n");
else{
fscanf(indiff, "%f", &x1);
fscanf(indiff, "%f", &h);
//start while loop
while ((fscanf(indiff, "%f\n", &diff_arr[i])) == 1)
{
//fscanf(indiff, "%f\n",&diff_arr[load_array]);
array_num++;
}
/*for (load_array=0;load_array<=50;load_array++)
{
fscanf(indiff, "%f\n",&diff_arr[load_array]);
array_num++;
*/}
printf("%f\n",diff_arr[0]);
printf("%i\n",array_num);
}
答案 0 :(得分:0)
在您的代码中,i
和array_num
都不会被初始化!
int i, array_num;
只是一个声明!将其修复为int i=0, array_num=0;
我相信您也希望在某个时候提升i
,否则它将永远为0.可能在这里:
while ((fscanf(indiff, "%f\n", &diff_arr[i++])) == 1)