1、题目
学生的记录由姓名和成绩组成且在主函数中通过结构体数组初始化,不要输入。请编写函数实现把最高分的学生通过结构体指针保存数据并输出。
要求:
- 使用结构体:
struct Student
{
char name[10];
int score;
};
- 请按下面给定数据给结构体数组的12位学生初始化:
{"HC105",85},{"HC103",76},{"HC102",98},{"HC104",85},
{"HC101",99},{"HC107",72},{"HC108",64},{"HC106",87},
{"HC115",85},{"HC113",94},{"HC112",99},{"HC114",99}
使用子函数: void StructMax(struct Student* a,int n,int* m) //n是原始数据个数,m保存最高分的人数
输出格式: 把最高分的学生信息输出
输出:
HC101 99
HC112 99
HC114 99
2、完整代码
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char name[10];
int score;
} students[20] = { {"HC105",85},{"HC103",76},{"HC102",98},{"HC104",85},
{"HC101",99},{"HC107",72},{"HC108",64},{"HC106",87},
{"HC115",85},{"HC113",94},{"HC112",99},{"HC114",99} };
int max(int a, int b)
{
return a > b ? a : b;
}
void StructMax(struct Student * a, int n, int * m)
{
int maxScore = -0x3f3f3f3f;
for(int i = 0; i < n; ++i)
maxScore = max(maxScore, students[i].score);
int cnt = 0;
for(int i = 0; i < n; ++i)
if(students[i].score == maxScore)
cnt ++;
*m = cnt;
for(int i = 0; i < n; ++i)
if(students[i].score == maxScore)
a[-- cnt] = students[i];
}
int main()
{
struct Student rnt[20];
int cnt;
StructMax(rnt, 12, &cnt);
for(int i = cnt-1; i >= 0; i--)
printf("%s %d\n", rnt[i].name, rnt[i].score);
return 0;
}