为什么来自stdlib的qsort无法使用双精度值?[C]

yak*_*yak 0 c double qsort

我写了一个简单的程序来整理数组。问题在于,仅当我需要数组具有double元素时,代码才可以使用int值...有帮助吗?

#include <stdio.h>
#include <stdlib.h>

double values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

int main()
{
    int n;

    printf("Before sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    qsort(values, 5, sizeof(double), cmpfunc);

    printf("\nAfter sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

工作代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double values[] = { 88, 56, 100, 2, 25 };

int compare (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b) return 1;
    else if (*(double*)a < *(double*)b) return -1;
    else return 0;
}

int main()
{
    int n;

    printf("Before sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    qsort(values, 5, sizeof(double), compare);

    printf("\nAfter sorting the list is: \n");
    for( n = 0 ; n < 5; n++ )
    {
        printf("%.2f ", values[n]);
    }

    printf("\n\n");

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

pio*_*kuc 5

您想对双打进行排序,但是将它们作为整数进行比较...请尝试以下比较功能:

int cmpfunc (const void * a, const void * b)
{
  if (*(double*)a > *(double*)b)
    return 1;
  else if (*(double*)a < *(double*)b)
    return -1;
  else
    return 0;  
}
Run Code Online (Sandbox Code Playgroud)