参考代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> //定义一个学生信息结构体 typedef struct { char *id; char *name; int score1; int score2; int score3; }Stu; //输入一个学生信息 Stu *inputStu() { Stu *stutmp; stutmp = (Stu*)malloc(sizeof(Stu)); if (stutmp == NULL) { return NULL; } char idtmp[100]; scanf("%s", idtmp); stutmp->id = (char*)malloc(strlen(idtmp) + 1); if (stutmp->id == NULL) { return NULL; } strcpy(stutmp->id, idtmp); char nametmp[100]; scanf("%s", nametmp); stutmp->name = (char*)malloc(strlen(nametmp) + 1); if (stutmp->name == NULL) { return NULL; } strcpy(stutmp->name, nametmp); scanf("%d", &stutmp->score1); scanf("%d", &stutmp->score2); scanf("%d", &stutmp->score3); return stutmp; } //输出信息 void printStu(Stu *students[], int N) { int totalscore1 = 0; int totalscore2 = 0; int totalscore3 = 0; int averscore1; int averscore2; int averscore3; int stutotalscores[N]; int i; for (i = 0; i < N; i++) { totalscore1 += students[i]->score1; totalscore2 += students[i]->score2; totalscore3 += students[i]->score3; stutotalscores[i] = students[i]->score1 + students[i]->score2 + students[i]->score3; } averscore1 = totalscore1 / N; averscore2 = totalscore2 / N; averscore3 = totalscore3 / N; printf("%d %d %d\n", averscore1, averscore2, averscore3); //找到最高分对应的学生信息并打印 int maxscores = 0; int maxindex = 0; for (i = 0; i < N; i++) { if (maxscores < stutotalscores[i]) { maxscores = stutotalscores[i]; maxindex = i; } } printf("%s %s %d %d %d\n", students[maxindex]->id, students[maxindex]->name, students[maxindex]->score1, students[maxindex]->score2, students[maxindex]->score3); } void freeStu(Stu *stu) { if (stu == NULL) return; free(stu->id); free(stu->name); free(stu); } int main() { int N; scanf("%d", &N); Stu *students[N]; int i; for (i = 0; i < N; i++) { students[i] = inputStu(); } printStu(students, N); for (i = 0; i < N; i++) { free(students[i]); } return 0; }
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题10.7 (C语言代码)scanf后面加个getchar(),收掉回车符,就可以用gets了浏览:1145 |
C语言程序设计教程(第三版)课后习题5.8 (C语言代码)浏览:930 |
不容易系列2 (C语言代码)浏览:589 |
最小公倍数 (C语言代码)浏览:863 |
不会做的浏览:873 |
WU-字符串比较 (C++代码)浏览:755 |
wu-淘淘的名单 (C++代码)浏览:1337 |
三角形 (C语言代码)浏览:904 |
母牛的故事 (C语言代码)浏览:940 |
哥德巴赫曾猜测 (C语言代码)浏览:715 |