# Thread: Averaging numbers in a while loop?

1. ## Averaging numbers in a while loop?

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!

2. Hmm. 40.3 / 19 = 2.1

Pay attention to your variables and how you calculate an average.

"total" might be a better name for your accumulator variable.

3. General run of thumb on calculating average in a program: calculate the sum in the loop; calculate the average after the loop.

Tim S.

4. Thank you! I got it!