I had to write a program that opens a file, reads a list of doubles, and then averages them. The result SHOULD be 40 something (i don't remember exactly and don't have time to average them again atm), and it's coming out as only 2.1. I do not understand why? Here is my code.
Code:
# include <stdio.h>
int main()
{
char filename[50];
double numbers;
printf ("Please enter the file that you wish to open: ");
scanf("%s", filename);
FILE *infile=fopen(filename, "r");
if(infile==NULL)
{
printf( "The file was not successfully opened");
}
int i = 0;
double average;
while (fscanf(infile, "%lf", &numbers)!=EOF)
{
average+= numbers;
i++;
numbers = numbers/i;
}
printf("The average is %.2lf\n", numbers);
fclose(infile);
return 0;
}
....and here is my doubles file
Code:
30.9
10.2
13.7
46.1
50.0
5.2
89.3
77.9
30.4
22.0
100.8
55.6
31.8
60.4
26.8
10.1
99.9
76.8
59.6
40.3
Thank you for any help!