[C语言]用结构体按分数高低降序输出学生的姓名和分数
1、题目
学生的记录由姓名和成绩组成,在主函数中循环输入4名学生的数据并用结构体数组存储,请编写函数StructSort,按分数的高低降序排列输出学生的姓名和分数。
要求: 使用结构体:
struct Student { char name[10]; int score; }
使用子函数: void StructSort(struct Student stu[], int n)
输入格式: 依次输入4名学生的姓名和分数
输出格式: 按分数降序输出学生信息
示例1:
输入:
KOBE 97
YAO 98
HC 99
JAMES 96
输出:
HC 99
YAO 98
KOBE 97
JAMES 96
2、完整代码
#include <stdio.h> struct Student { char name[10]; int score; } students[5]; void swap(struct Student stu[], int a, int b) { struct Student s = stu[a]; stu[a] = stu[b]; stu[b] = s; } void StructSort(struct Student stu[], int n) { for(int i = 1; i <= n; ++i) { int m = i; for(int j = i + 1; j <= n; ++j) { if(stu[m].score < stu[j].score) m = j; } if(m != i) swap(stu, m, i); } } int main() { for(int i = 1; i <= 4; ++i) scanf("%s%d", students[i].name, &students[i].score); StructSort(students, 4); for(int i = 1; i <= 4; ++i) printf("%s %d\n", students[i].name, students[i].score); return 0; }
3、截图
本文作者:Dancing-Pierre
本文链接:https://www.cnblogs.com/wyc-1009/p/17548025.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步