#include #include "fields.h" typedef struct { IS is; int field; } TokenGen; TokenGen *new_tokengen(char *fn) { TokenGen *tg; tg = (TokenGen *) malloc(sizeof(TokenGen)); tg->is = new_inputstruct(fn); if (tg->is == NULL) return NULL; tg->field = -1; return tg; } char *tokengen_get_token(TokenGen *tg) { char *s; while(tg->field == -1 || tg->field >= tg->is->NF) { if (get_line(tg->is) < 0) return NULL; if (tg->is->text1[0] == '#') { tg->field = -1; } else { tg->field = 0; } } s = tg->is->fields[tg->field]; tg->field++; return s; } 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: variance3 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); }