zoukankan      html  css  js  c++  java
  • 最小年龄的3个职工

    题目截图:

     

    思路:

      关键字顺序:年龄>工号>姓名,从小到大自定义 cmp 函数,然后使用内置的 qsort 函数即可。qsort 的用法详见另一篇博客

    代码如下:

     1 /*
     2     最小年龄的3个职工 
     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     int id;                // 职工号        
    15     char name[11];        // 姓名 
    16     int age;            // 年龄 
    17 } staff; 
    18 staff staffs[31];        // 存储所有员工数据 
    19 
    20 // 自定义排序
    21 // 关键字顺序:年龄>工号>姓名,从小到大。 
    22 int cmp(const void* a, const void* b) {
    23     staff* c = (staff*)a;
    24     staff* d = (staff*)b;
    25     if(c->age == d->age) {
    26         if(c->id == d->id) {
    27             return strcmp(c->name, d->name);
    28         } else {
    29             return c->id - d->id;
    30         }
    31     } else {
    32         return c->age - d->age;
    33     }
    34 }
    35 
    36 int main() {
    37     int n, i;
    38     while(scanf("%d", &n) != EOF) {
    39         for(i=0; i<n; ++i) {            // 输入员工信息 
    40             staff s;
    41             scanf("%d %s %d", &s.id, s.name, &s.age);
    42             staffs[i] = s;
    43         }
    44         // 按要求排序 
    45         qsort(staffs, n, sizeof(staffs[0]), cmp);
    46         // 输出结果行数为N和3的较小值
    47         int min = (n<3 ? n : 3);
    48         for(i=0; i<min; ++i) {            // 按要求输出 
    49             staff s = staffs[i];
    50             printf("%d %s %d
    ", s.id, s.name, s.age);
    51         }
    52     } 
    53 
    54     return 0;
    55 }
  • 相关阅读:
    python2和3使用pip时的问题
    Python爬虫-爬取百度贴吧帖子
    Python爬虫-爬取糗事百科段子
    keras例子-matchnet
    win10-Anaconda2-Theano-cuda7.5-VS2013
    caffe-win10-cifar10另
    PHP——0126最初
    PHP——动态随机数
    PHP——投票
    PHP——内测:联系人管理
  • 原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest16.html
Copyright © 2011-2022 走看看