#include #include "tokengen.h" main(int argc, char **argv) { int n, i; double *values; double avg; double variance; TokenGen *tg; char *s; /* First you need to get n from the command line arguments. */ if (argc != 2) { fprintf(stderr, "usage: variance5 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 token generator */ tg = new_tokengen(NULL); for (i = 0; i < n; i++) { s = tokengen_get_token(tg); if (s == NULL) exit(1); if (sscanf(s, "%lf", &(values[i])) != 1) 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); }