Advertisement
cd62131

load_file sort_list print_average

Feb 1st, 2019
494
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. typedef struct dt dt;
  5. struct dt {
  6.   int student;
  7.   char course[20];
  8.   int score;
  9.   dt *next;
  10. };
  11. static dt *head;
  12. static void load_file(void) {
  13.   FILE *file = fopen("data.txt", "r");
  14.   int s;
  15.   char c[20];
  16.   int sc;
  17.   head = NULL;
  18.   while (fscanf(file, "%d%s%d", &s, c, &sc) != EOF) {
  19.     dt *new = calloc(sizeof(*new), 1);
  20.     new->student = s;
  21.     strcpy(new->course, c);
  22.     new->score = sc;
  23.     new->next = head;
  24.     head = new;
  25.   }
  26. }
  27. static void show_dt(void) {
  28.   for (dt *p = head; p; p = p->next) {
  29.     printf("%d %s %d\n", p->student, p->course, p->score);
  30.   }
  31. }
  32. static void remove_one(dt *d) {
  33.   if (head == d) {
  34.     head = head->next;
  35.     return;
  36.   }
  37.   for (dt *p = head->next, *prev = head; p; prev = p, p = p->next) {
  38.     if (p == d) {
  39.       prev->next = p->next;
  40.       return;
  41.     }
  42.   }
  43. }
  44. static void sort_list(void) {
  45.   if (!head) {
  46.     return;
  47.   }
  48.   dt *min = head;
  49.   for (dt *p = head->next; p; p = p->next) {
  50.     if (p->student < min->student) {
  51.       min = p;
  52.     }
  53.   }
  54.   remove_one(min);
  55.   sort_list();
  56.   min->next = head;
  57.   head = min;
  58. }
  59. static void print_average(void) {
  60.   int count = 0, total = 0;
  61.   for (dt *p = head; p; p = p->next) {
  62.     ++count;
  63.     total += p->score;
  64.     if (p->next && p->next->student == p->student) {
  65.       continue;
  66.     }
  67.     printf("%d %d %d\n", p->student, count, total / count);
  68.     count = total = 0;
  69.   }
  70. }
  71. int main(void) {
  72.   load_file();
  73.   sort_list();
  74.   print_average();
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement