/* * This program reads numbers into an array from a file called "numbers", o * then prints the average and standard deviations of the numbers. */ #include #include #define MAX_NUMBERS 1000 /* This function reads the numbers from the file "numbers", returning * with the numbers of items read */ int read_numbers (float v[]) { int i; float num; FILE *fp; /* open the file */ fp = fopen ("numbers", "r"); /* fp is NULL? complain. */ if (!fp) { fprintf (stderr, "read_numbers: can't open file!\n"); exit (1); } /* loop until break */ for (i=0;;) { /* read an item */ fscanf (fp, "%f", &num); /* end of file? break. */ if (feof (fp)) break; /* too many numbers? uh-oh... */ if (i >= MAX_NUMBERS) { fprintf (stderr, "read_numbers: too many numbers!\n"); exit (1); } /* put the number into the array, then increment the index */ v[i++] = num; } fclose (fp); /* i is the number of items read */ return i; } /* this function finds the arithmetic mean of numbers in an array */ float find_average (float v[], int n) { int i; float sum; /* can't divide by zero... */ if (n < 1) { fprintf (stderr, "find_average: too few numbers!\n"); exit (1); } /* find total of numbers */ sum = 0; for (i=0; i