1 #define _CRT_SECURE_NO_WARNINGS //关闭安全检查 2 #include<stdio.h> 3 #include<stdlib.h> 4 5 //定义结构体类型 6 struct ST 7 { 8 int ID; 9 char name[20]; 10 float score[3]; 11 }; 12 13 //方法1 : 结构体数组作为函数参数 开销大 14 float avg(struct ST sts[], int n) 15 { 16 float sum = 0, avg; 17 for (int i = 0; i < n; i++) 18 { 19 for (int j = 0; j < 3; j++) 20 { 21 sum += sts[i].score[j]; 22 } 23 } 24 avg = sum / n / 3; 25 return avg; 26 } 27 28 //方法2 : 结构体数组指针作为函数参数 开销小 29 float avg1(struct ST *p, int n) 30 { 31 float sum = 0, avg; 32 for (int i = 0; i < n; i++) 33 { 34 for (int j = 0; j < 3; j++) 35 { 36 sum += p[i].score[j]; 37 } 38 } 39 avg = sum / n / 3; 40 return avg; 41 } 42 43 //输出最高分数学生信息 44 void high(struct ST *p, int n) 45 { 46 int index = 0; 47 float max = 0, sum = 0; 48 for (int i = 0; i < n; i++) 49 { 50 for (int j = 0; j < 3; j++) 51 { 52 sum = p[i].score[0] + p[i].score[1] + p[i].score[2]; 53 if (sum > max) 54 { 55 max = sum; 56 index = i; 57 } 58 } 59 } 60 printf("最高学生信息为:\n"); 61 //(p+index)->ID 等价于 p[index].ID 62 printf("学号:%d\n", (p+index)->ID); 63 printf("姓名:%s\n", p[index].name); 64 printf("成绩:%.2f, %.2f, %.2f\n", p[index].score[0], p[index].score[1], p[index].score[2]); 65 } 66 67 int main() 68 { 69 int i, j; 70 struct ST sts[5]; 71 for (i = 0; i < 5; i++) 72 { 73 printf("请输入第%d个学生信息\n", i+1); 74 scanf("%d", &sts[i].ID); 75 //加不加&都可以 76 scanf("%s", sts[i].name); 77 printf("输入各科成绩\n"); 78 for (j = 0; j < 3; j++) 79 { 80 scanf("%f", &sts[i].score[j]); 81 } 82 } 83 84 printf("平均成绩为:%f\n", avg1(sts, 5)); 85 high(sts, 5); 86 system("pause"); 87 return 0; 88 }
时间: 2024-10-14 10:58:10