• 第 16 章 C 预处理器和 C 库(qsort() 函数)


     1 /*----------------------------------------
     2     qsorter.c -- 用 qsort() 排序一组数字
     3 ----------------------------------------*/
     4 
     5 #include <stdio.h>
     6 #include <stdlib.h>        //提供函数 rand() 原型
     7 
     8 #define NUM 40
     9 
    10 void fillarray(double ar[], int n);
    11 void showarray(const double ar[], int n);
    12 int mycomp(const void *p1, const void *p2);
    13 
    14 int main()
    15 {
    16     double vals[NUM];
    17 
    18     fillarray(vals, NUM);
    19     puts("Random list:");
    20     showarray(vals, NUM);
    21 
    22     qsort(vals, NUM, sizeof(double), mycomp);
    23     puts("
    Sorted list:");
    24     showarray(vals, NUM);
    25 
    26     return 0;
    27 }
    28 
    29 void fillarray(double ar[], int n)
    30 {
    31     for (int index = 0; index != n; ++index)
    32         ar[index] = (double)(rand()) / ((double)(rand()) + 0.1);
    33 }
    34 
    35 void showarray(const double ar[], int n)
    36 {
    37     int index = 0;
    38 
    39     for (; index != n; ++index)
    40     {
    41         printf("%9.4f ", ar[index]);
    42         if (index % 6 == 5) putchar('
    ');
    43     }
    44 
    45     if (index % 6 != 0) putchar('
    ');
    46 }
    47 
    48 int mycomp(const void *p1, const void *p2)
    49 {
    50     const double *a1 = (double*)p1;
    51     const double *a2 = (double*)p2;
    52 
    53     if (*a1 > *a2)
    54         return 1;
    55     else if (*a1 == *a2)
    56         return 0;
    57     else
    58         return -1;
    59 }
    qsorter.c

  • 相关阅读:
    CF459E Pashmak and Graph
    cf478D Red-Green Towers
    cf255C Almost Arithmetical Progression
    准备做,但是还没做的
    CF219C hoosing Capital for Treeland
    最小中间和
    【NO.9】jmeter
    【设计用例】站内信
    【有意思的BUG】客户端无厘头 已连网的场景初始化太慢 未连网的场景异常崩溃
    禅道BUG系统
  • 原文地址:https://www.cnblogs.com/web1013/p/9258282.html
Copyright © 2020-2023  润新知