1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #include <stdio.h> #include <string.h> #include <stdlib.h> #define N 20 #define M 3 struct stu { char name[N]; int score[M]; double avg; };
void swap(struct stu *m, struct stu *n) { stu t = *m; *m = *n; *n = t; } void input(struct stu *s, int n) { double sum = 0; for (int i = 0; i < n; i++) { printf("请输入姓名:"); scanf("%s", s[i].name); printf("请输入分数(英语数C):"); for (int j = 0; j < M; j++) scanf("%d", &s[i].score[j]); printf("\n"); } } void sort(struct stu *s, int n) { int i, j; for (i = 0; i < n; i++) { double sum = 0; for (j = 0; j < M; j++) sum += s[i].score[j]; s[i].avg = sum / M; } for (i = 1; i < n; i++) for (j = 0; j < n - i; j++) if (s[j].avg < s[j + 1].avg) swap(&s[j], &s[j + 1]); else if ((s[j].avg == s[j + 1].avg) && (strcmp(s[j].name, s[j + 1].name) < 0)) swap(&s[j], &s[j + 1]); } void save(struct stu *s, int n) { FILE *fp = fopen("test.txt", "w"); for (int i = 0; i < n; i++) { fprintf(fp, "%s\t", s[i].name); for (int j = 0; j < M; j++) fprintf(fp, "%d\t", s[i].score[j]); fprintf(fp, "%f\n", s[i].avg); } fclose(fp); } void output(struct stu *s, int n) { int i = 0; FILE *fp = fopen("test.txt", "r"); while (!feof(fp)) { fscanf(fp, "%s", s[i].name); for (int j = 0; j < M; j++) fscanf(fp, "%d", &s[i].score[j]); fscanf(fp, "%f", &s[i].avg); i++; } fclose(fp);
for (i = 0; i < n; i++) { printf("%s\t", s[i].name); for (j = 0; j < M; j++) printf("%d ", s[i].score[j]); printf("%.1lf", s[i].avg); printf("\n"); } } int main() { int n; struct stu s[N]; printf("input n:"); scanf("%d", &n); input(s, n); sort(s, n); save(s, n); output(s, n); return 0; }
|