题目:给出班里某门课程的成绩单,请你按成绩从高到低对成绩单排序输出,如果有相同分数则名字字典序小的在前。
代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
struct Stu
{
char name[20];//学生名字
int score;//学生成绩
};
int main()
{
int n;//有n个学生,0<n<20
scanf("%d", &n);//输入学生的个数
struct Stu s[20];
int i;
for (i = 0; i < n; i++)
{
scanf("%s %d", s[i].name, &s[i].score);//输入学生的名字和成绩
}
int j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1; j++)
{
if (s[j].score < s[j + 1].score)//将学生的成绩从高到低排序
{
struct Stu tmp;//使用中间变量tmp来进行交换
tmp = s[j];
s[j] = s[j + 1];
s[j + 1] = tmp;
}
if (s[j].score == s[j + 1].score)//如果成绩相同则名字字典序小的在前。
{
if (strcmp(s[j].name, s[j + 1].name) > 0)
{
struct Stu tmp;
tmp = s[j];
s[j] = s[j + 1];
s[j + 1] = tmp;
//使用库函数strcmp()来比较名字字典序的的大小 -- 使用该函数前要引头文件:#include<string.h>。
//如果strcmp()的返回值大于0,则说明前者名字字典序大于后者0。
//反之,如果小于0,则前者小于后者(无需交换顺序)。
//如果等于0,则说明两者的名字字典序大小相同。
}
}
}
}
for (i = 0; i < n; i++)
{
printf("%s %d\n", s[i].name, s[i].score);//打印学生的名字和成绩
}
return 0;
}
如有不足,还望指出,感谢。