Domanda

I'm new to using qsort, and I'm attempting to qsort a predefined array of doubles, unfortunately the result I receive is all 0's after the array has been sorted using qsort. I'm completely lost, and any advice would be greatly appreciated. Here is the code I am using to sort this array of doubles.

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

double stuff[] = {255, 1, 5, 39.0};
qsort(stuff, 4, sizeof(double), compare);
int i;
for(i = 0; i < 4; i++){
    printf("%d %s", stuff[i], " ");
}
È stato utile?

Soluzione

Your problem is the way you are printing the result with your printf() function. To print double values, you need to use %f, like this:

printf("%f ", stuff[i]);

Also, just a sidenote: you don't need these else statements in your compare function, since once the condition is evaluated as true, it will return the function.

Altri suggerimenti

As already noted, the problem is in the format specifier you used with printf(): %d (which you used) is not good for doubles; you should use something like %f or %g instead. See this Q&A on StackOverflow for more details.

Something like:

printf("%g ", stuff[i]);

should be just fine.

(Note that you don't need to pass "%s" and single-space string literal to printf() either.)

Moreover, I'd like to show you how to better write your compare() function:

  1. You can assign the raw void* pointers to some constant value at the beginning of function body, to avoid repeating the (ugly) casts, and making the code clearer and more readable.

  2. You may want to simplify your if...else if...else structure, and just use a simpler if...return structure.

Something like this:

static int compare(const void * a, const void * b) 
{
    const double lhs = *(const double *)a;
    const double rhs = *(const double *)b;

    if (lhs > rhs)
        return 1;

    if (lhs < rhs)
        return -1;

    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top