发布网友 发布时间:2022-04-22 01:43
共1个回答
热心网友 时间:2023-08-26 15:57
#include <stdio.h>
#include <stdlib.h>
typedef struct _STUDENT_INFO {
int id;// 序号
int rank;// 名次
int achievement;// 成绩
} STUDENT_INFO, *PSTUDENT_INFO;
// 交换2个学生的信息
void SwapStudentInfo(PSTUDENT_INFO stu1, PSTUDENT_INFO stu2)
{
int tmp;
// 交换ID
tmp = stu1->id;
stu1->id = stu2->id;
stu2->id = tmp;
// 交换成绩
tmp = stu1->achievement;
stu1->achievement = stu2->achievement;
stu2->achievement = tmp;
}
// 计算排名的函数
void CalculateRank(PSTUDENT_INFO students, int n)
{
int i, j, tmp;
// 按照成绩排序
for (i=0; i<n-1; ++i)
{
for (j=i+1; j<n; ++j)
{
if (students[i].achievement < students[j].achievement)
{
SwapStudentInfo(students+i, students+j);
}
}
}
// 根据排序后的成绩计算排名
for (i=0, j=1; i<n; ++i)
{
students[i].rank = j;
if (students[i].achievement != students[i+1].achievement)
{
++j;
}
}
}
// 显示排名的函数
void DisplayRank(PSTUDENT_INFO students, int n)
{
int i;
printf("\n%-10s%-10s%-10s\n", "排名", "序号", "成绩");
for (i=0; i<n; ++i)
{
printf("%-10d%-10d%-10d\n", students[i].rank, students[i].id, students[i].achievement);
}
}
void main()
{
int n, i;
PSTUDENT_INFO students;
// 输入学生人数
printf("请输入学生人数:");
scanf("%d", &n);
// 动态分配n个学生信息的结构体
students = (PSTUDENT_INFO)malloc(n * sizeof(STUDENT_INFO));
// 输入n个学生的成绩
printf("\n请输入学生成绩:");
for (i=0; i<n; ++i)
{
students[i].id = i+1;// 初始化各个学生的序号
scanf("%d", &students[i].achievement);
}
// 计算排名
CalculateRank(students, n);
// 显示排名
DisplayRank(students, n);
// 释放students
free(students);
}