定义结构体struct stu,编写成绩排名函数:void sort(struct stu *ps,int n),对结构体数组按成绩排名。 程序功能为读入整数N(N<100),再读入N个学生的学号(整型)和成绩(实数)。按样例输出排名。
输入格式:
见样例
输出格式:
第一列是名次,注意并列情况;第二列是学号,第三列是成绩(2位小数)。
输入样例:
5
101 99
102 100
103 50
104 80
105 99
结尾无空行
输出样例:
1 102 100.00
2 101 99.00
2 105 99.00
4 104 80.00
5 103 50.00
结尾无空行
#include<stdio.h>
struct stu
{
int td;
int sid;
float score;
};
void sort(struct stu* ps, int n);
int main()
{
struct stu student[100];
int n,i;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d%f", &student[i].sid, &student[i].score);
}
sort(student, n);
for (i = 0; i < n-1; i++)
{
printf("%d %d %.2f\n", student[i].td,student[i].sid, student[i].score);
}
printf("%d %d %.2f", student[i].td, student[i].sid, student[i].score); //最后一行单独输出防止空行
return 0;
}
void sort(struct stu* ps, int n)
{
int i, j,k,t;
float a;
for (i =0; i < n ; i++) //排序
{
k = i;
for(j=i;j<n;j++)
{
if ((ps + j)->score > (ps + k)->score)
k = j;
}
t = (*(ps + i)).score;
(*(ps + i)).score =( *(ps + k)).score;
(*(ps + k)).score = t;
a = (*(ps + i)).sid;
(*(ps + i)).sid = (*(ps + k)).sid;
(*(ps + k)).sid = a;
}
j = 1;
(*ps).td = 1;
for (i = 1; i < n; i++)
{
if ((*(ps + i)).score < (*(ps + i - 1)).score) //排名
{
(*(ps + i)).td = (*(ps + i - 1)).td+j;
j = 1;
}
else
{
(*(ps + i)).td = (*(ps + i - 1)).td;
j++;
}
}
}