简体   繁体   中英

qsort (float 2D array) bug in this value <stdlib.h>

I tried to made first value = first value / second value and sort it:

#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");
        }
    }

before qsort -------- after qsort -----  my expect


1.0 10.0 ------------- 0.5 10.0 -------- 0.4  5.0    

0.5 10.0 ------------- 1.0 5.0  -------- 0.5  10.0   

1.0 5.0  ------------- 0.4 5.0  -------- 1.0  5.0    

0.4 5.0  ------------- 1.0 10.0 -------- 1.0  10.0 

After qsort output is weird. Can you tell me what I misunderstand?

Your comparison function is not correct. It (implicitly) converts the difference of two floating point values by truncating it to an integer. Therefore two floating point values are considered equal if their difference is strictly less than 1.0 .

A correct comparison function would be

int cmp (const void * a, const void * b)
{
    float x = *(float*)a;
    float y = *(float*)b;
    return x < y ? -1 : x == y ? 0 : 1;
}

With that modification, the output of your program is

0.4 5.0 
0.5 10.0 
1.0 10.0 
1.0 5.0 

so the array is correctly sorted with respect to the first "column".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM