成绩排序
题目截图:

思路:
定义一个结构体,然后使用 C语言内置的 qsort函数,需要自定义 cmp函数。详情见另一篇博客。
代码如下:
1 /*
2 成绩排序
3 */
4
5 #include <stdio.h>
6 #include <string.h>
7 #include <math.h>
8 #include <stdlib.h>
9 #include <time.h>
10 #include <stdbool.h>
11
12 // 结构体定义
13 typedef struct {
14 char name[101]; // 姓名
15 int age; // 年龄
16 int socre; // 分数
17 } student;
18
19 // 用于储存输入的学生数据
20 student students[1001];
21
22 // 自定义排序
23 int cmp(const void* a, const void* b) {
24 student* c = (student*)a;
25 student* d = (student*)b;
26 if(c->socre != d->socre) { // 若分数不同
27 return c->socre - d->socre; // 按分数升序排序
28 } else { // 若分数相同
29 if(strcmp(c->name, d->name) != 0) { // 若名字不同
30 return strcmp(c->name, d->name); // 按名字字典序升序排序
31 } else { // 若名字相同
32 return c->age - d->age; // 按年龄升序排序
33 }
34 }
35 }
36
37 int main() {
38 int N;
39 while(scanf("%d", &N) != EOF) {
40 int i;
41 for(i=0; i<N; ++i) { // 输入学生信息,并存储
42 student s;
43 scanf("%s %d %d", s.name, &s.age, &s.socre);
44 students[i] = s;
45 }
46 // 按要求排序
47 qsort(students, N, sizeof(students[0]), cmp);
48 for(i=0; i<N; ++i) { // 按要求输出学生信息
49 student s = students[i];
50 printf("%s %d %d\n", s.name, s.age, s.socre);
51 }
52 }
53
54 return 0;
55 } 相关推荐
89243453 2020-08-24
Erick 2020-08-21
earthhouge 2020-07-19
klarclm 2020-06-14
拉斯厄尔高福 2020-06-02
Jaystrong 2020-06-02
hongsheyoumo 2020-06-02
twater000 2020-05-30
adonislu 2020-05-17
Haopython 2020-05-09
浅梦墨汐 2020-05-12
shenwenjie 2020-05-09
fengjing81 2020-05-08
lihuifei 2020-05-04
wbczyh 2020-05-03
LychieFan 2020-04-30
luckymaoyy 2020-04-25
Cypress 2020-04-25