为了能到远方,脚下的每一步都不能少.|

Dancing-Pierre

园龄:1年10个月粉丝:3关注:0

[C语言]用结构体按分数高低降序输出学生的姓名和分数

[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 中国大陆许可协议进行许可。

posted @   Dancing-Pierre  阅读(40)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起