有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序
//我把声明文件放在.h文件中
//把函数实现部分放在.m文件中
//最后的函数调用放在主函数main中,代码如下
.h文件
typedef struct student{
char name[10]; //存储学生姓名
float score; //存储学生成绩
int age; //存储学生年龄
}Stud;
//输出结构体成员
void outputStudent(Stud stu);
//输出所有成员的信息
void outputAllStudent(Stud b[], int count);
.m文件
//输出结构体成员
void outputStudent(Stud stu){
printf("Name = %s Score = %.2f Age = %d", stu.name, stu.score, stu.age);
}
//输出所有学生的信息
void outputAllStudent(Stud b[], int count){
for (int i = 0; i < count; i++) {
printf("\n");
outputStudent(b[i]);
}
}
主函数main内
//1.有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序
Stud a[5] ={
{"oubama", 59.9, 44},
{"xilayi", 76.0, 55},
{"baideng",49.01, 50},
{"bushen",71.9, 66},
{"kelindun",83.3, 33},
};
//输出所有学生结构体成员
printf("输出前:");
outputAllStudent(a, 5);
printf("\n");
//1)编程按学生的成绩升序排序
printf("成绩生序排序后为:");
for (int i = 0; i < 5 - 1; i++) {
for (int j = 0; j < 5 - 1 - j; j++) {
if (a[j].score > a[j + 1].score) {
Stud tempStud = {0};
tempStud = a[j];
a[j] = a[j + 1];
a[j + 1] = tempStud;
}
}
}
outputAllStudent(a, 5);
//2)按学生的姓名降序排序
printf("\n按学生姓名排序后:");
for (int i = 0; i < 5 - 1; i++) {
for (int j = 0; j < 5 - 1 - i; j++) {
if (strcmp(a[j].name, a[j + 1].name) < 0) {
Stud tempStud = {0};
tempStud = a[j];
a[j] = a[j + 1];
a[j + 1] = tempStud;
}
}
}
outputAllStudent(a, 5);
//2)按年龄从低到高排序
printf("\n按年龄从低到高排序后:");
for (int i = 0; i < 5 - 1; i++) {
for (int j = 0; j < 5 - 1 - i; j++) {
if (a[j].age > a[j + 1].age) {
Stud tempStud = {0};
tempStud = a[j];
a[j] = a[j + 1];
a[j + 1] = tempStud;
}
}
}
outputAllStudent(a, 5);