C 此值中的qsort(浮点2D数组)错误<;stdlib.h>;
我尝试将C 此值中的qsort(浮点2D数组)错误<;stdlib.h>;,c,arrays,floating-point,quicksort,qsort,C,Arrays,Floating Point,Quicksort,Qsort,我尝试将第一个值=第一个值/第二个值进行排序: #include<stdlib.h> #include<stdio.h> int cmp (const void * a, const void * b) {return ( *(float*)a - *(float*)b );} int main() { float Array[4][2]= {{10,10},
第一个值=第一个值/第二个值
进行排序:
#include<stdlib.h>
#include<stdio.h>
int cmp (const void * a, const void * b)
{return ( *(float*)a - *(float*)b );}
int main()
{
float Array[4][2]= {{10,10},
{5, 10},
{5, 5 },
{2, 5}};
int i,j;
for(j=0;j<4;j++) //first value = first value / second value
{
Array[j][0]=Array[j][0]/Array[j][1];
}
qsort(Array, 4, 2*sizeof(Array[0][0]), cmp);
for(j=0;j<4;j++) //JUST PRINTF
{
for(i=0;i<2;i++)
printf("%.1f ",Array[j][i]);
printf("\n");
}
}
qsort之后的输出很奇怪。你能告诉我我误解了什么吗?你的比较函数不正确。它(隐含地) 转换两个浮点值之差 通过将其截断为整数。因此有两个浮点数 如果严格限制了值之间的差异,则认为值相等 小于
1.0
正确的比较函数是
int cmp (const void * a, const void * b)
{
float x = *(float*)a;
float y = *(float*)b;
return x < y ? -1 : x == y ? 0 : 1;
}
因此,数组相对于第一个“列”进行了正确排序
int cmp (const void * a, const void * b)
{
float x = *(float*)a;
float y = *(float*)b;
return x < y ? -1 : x == y ? 0 : 1;
}
0.4 5.0
0.5 10.0
1.0 10.0
1.0 5.0