【发布时间】:2014-01-02 06:49:13
【问题描述】:
我编写了一个简单的程序来整理我的数组。问题是代码仅在我需要我的数组具有 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);
}
工作代码:
#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);
}
【问题讨论】:
-
cmpfnc被转换为int*。 -
如果你有双打,那你为什么要在比较函数中转换成 int* 呢?
-
您不能只说“哦,这些是整数”——它们是双精度数。尝试使用 sgn: return ( sgn((double)a - (double)b) );
-
@hacks 为什么你需要
cmpfunc的参数? -
@hacks
cmpfunc是用于qsort的比较函数,我不知道你在说什么