参考代码如下:
#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.3 (C语言代码)浏览:593 |
DNA (C++代码)浏览:671 |
C语言程序设计教程(第三版)课后习题10.1 (C语言代码)浏览:1523 |
打水问题 (C语言代码)浏览:1156 |
校门外的树 (C语言代码)浏览:990 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:555 |
蚂蚁感冒 (C语言代码)浏览:1409 |
【偶数求和】 (C语言代码)浏览:460 |
Tom数 (C语言代码)浏览:758 |
罗列完美数 (C语言代码)浏览:519 |