/* This program finds the average and standard deviation of numbers * in a file. It reads the file first, finding the average, then * again, finding the sum of squares of differences. * (Note: you can do it all in one pass, but then what would be the * fun in that?) */ #include #include int main () { FILE *f; /* file pointer */ int n; /* number of items read in */ float num, /* number to read in */ sum, /* sum of all the numbers */ average, /* average of the numbers */ diff, /* difference of a number with average */ sumdiffsq, /* sum of the squares of the differences */ sd; /* standard deviation */ /* initialize sum accumulator to 0 */ sum = 0.0; /* open the file called "numbers" for reading */ f = fopen ("numbers", "r"); /* get a number from the file */ fscanf (f, "%f", &num); /* while we haven't reached the end of the file... */ while (!feof (f)) { /* add the number to the total */ sum += num; /* we have one more number, so add one to n */ n++; /* get another number */ fscanf (f, "%f", &num); } /* close the file */ fclose (f); /* figure out the average from sum and n */ average = sum / n; /* start the sum of squared differences accumulator as 0 */ sumdiffsq = 0.0; /* open the file again for reading */ f = fopen ("numbers", "r"); /* get the first number from the file */ fscanf (f, "%f", &num); /* while we're not at the end of the file... */ while (!feof (f)) { /* find the difference of the number with the average */ diff = num - average; /* add its square to the total */ sumdiffsq += diff * diff; /* get another number from the file */ fscanf (f, "%f", &num); } /* close the file */ fclose (f); /* finally calculate the standard deviation */ sd = sqrt (sumdiffsq / (n-1)); /* print the average and sd */ printf ("average = %f\tsd = %f\n", average, sd); }