码迷,mamicode.com
首页 > 编程语言 > 详细

成绩排序

时间:2018-02-08 20:19:47      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:algorithm   分享图片   note   题目   mic   idt   .so   algo   字典序   

题目截图:

技术分享图片

 

思路:

  定义一个结构体,然后使用 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 }

 

成绩排序

标签:algorithm   分享图片   note   题目   mic   idt   .so   algo   字典序   

原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest12.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!