Write a program called stats that computes statistics about numbers. The input will read from stdin. The first line will contain an integer that is the count of the numbers that follow. The remaining numbers will be floating point. Your program must contain the following functions:
void read_doubles(int n, double a[n])
will read n doubles into the array.void max_min(int n, double a[n], double *max, double *min)
will compute the max and min of the items in the array.double sum(int n, double a[n])
will return the sum of the numbers in the array.double mean(int n, double a[n])
will return the mean of the numbers in the array.double median(int n, double a[n])
will return the median of the numbers in the array.double variance(int n, double a[n])
will return the variance of the numbers in the array.double stddev(int n, double a[n])
will return the standard deviation of the numbers in the array.
The easy way to compute the median is to sort the array. Then the median is the middle element, if n is odd, or the average of the two middle elements, if n is even.
To sort the
array, you can use the qsort function, which implements the quicksort algorithm. You call it
like this: qsort(a, n, sizeof(double), compare);
where a is the array of
doubles and n is the size. The last argument, compare, is a function that compares two items
from the array (so two doubles).
Defining compare is a little tricky, because it takes two pointers to doubles as arguments. However, because qsort is designed to sort an array of any type, the arguments are declared as void *. Here is a comparison function that will work. Use this EXACTLY if you want it to work.
int compare(const void *x, const void *y) { double xx = * (double *) x; double yy = * (double *) y; if (xx < yy) return -1; else if (xx > yy) return 1; else return 0; }
On Wednesday I will explain more about how it works.
To compute the variance, find the sum of (a[i] - mean)2 and divide by the count.
The standard deviation is the square root of the variance.
The main program will call the functions to read in the numbers and do the calculations. The results will be printed in main in two columns. The first column will label the output and the second will be the result of the calculation. Print the count of the numbers at the beginning. The other functions must NOT do any output.
If the input is:
4 3.2 1.0 2.5 7.6
the output should look like this:
count: 4 min: 1.00000000 max: 7.60000000 sum: 14.30000000 median: 2.85000000 mean: 3.57500000 variance: 6.03187500 stddev: 2.45598758