#include #include "fields.h" main(int argc, char **argv) { int n, i, j; double *values; double avg; double variance; IS is; /* First you need to get n from the command line arguments. */ if (argc != 2) { fprintf(stderr, "usage: variance2 n\n"); exit(1); } n = atoi(argv[1]); if (n <= 0) exit(1); /* Next, you need to malloc() space for n doubles. */ values = (double *) malloc(sizeof(double)*n); /* Next, you read them in using the fields library */ is = new_inputstruct(NULL); i = 0; while (i < n && get_line(is) >= 0) { if (is->text1[0] != '#') { for (j = 0; j < is->NF; j++) { if (i < n) { if (sscanf(is->fields[j], "%lf", &(values[i])) != 1) exit(1); i++; } } } } if (i < n) exit(1); /* Next, you compute their average. */ avg = 0; for (i = 0; i < n; i++) { avg += values[i]; } avg /= n; /* Now, you compute the sum of the squares of the differences. */ variance = 0; for (i = 0; i < n; i++) { variance += ((values[i]-avg)*(values[i]-avg)); } /* Finally, you compute the variance and print them both out. */ variance /= n; printf("Average: %lf\n", avg); printf("Variance: %lf\n", variance); }