Advertisement
cd62131

course statistics

Jan 13th, 2019
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include <float.h>
  2. #include <math.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. static void statistics(const char *fname, const char *suffix,
  6.                        const char *format) {
  7.   char to_name[BUFSIZ];
  8.   sprintf(to_name, "%s.%s", fname, suffix);
  9.   FILE *from = fopen(fname, "r");
  10.   FILE *to = fopen(to_name, "w");
  11.   if (!from || !to) {
  12.     exit(1);
  13.   }
  14.   int n = 0;
  15.   double sum = 0., max = -DBL_MAX, min = DBL_MAX;
  16.   char buf[BUFSIZ];
  17.   while (fgets(buf, BUFSIZ, from)) {
  18.     double e;
  19.     if (sscanf(buf, format, &e) != 1) {
  20.       exit(1);
  21.     }
  22.     ++n;
  23.     sum += e;
  24.     max = fmax(max, e);
  25.     min = fmin(min, e);
  26.   }
  27.   fprintf(to, "%f\t%f\t%f\n", sum / n, max, min);
  28.   fclose(from);
  29.   fclose(to);
  30. }
  31. int main(void) {
  32.   struct {
  33.     char *suffix, *format;
  34.   } course[] = {{"physics", "%*s%lf%*lf"}, {"chemistry", "%*s%*lf%lf"}};
  35.   for (size_t i = 0; i < sizeof(course) / sizeof(course[0]); ++i) {
  36.     statistics("result.dat", course[i].suffix, course[i].format);
  37.   }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement