原题链接:[编程入门]结构体之成绩统计2
参考代码如下:
#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语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复