简体   繁体   English

使用 qsort 对 C 中的结构数组进行排序

[英]Using qsort to sort an array of structs in C

I tried to sort an array of Products by its unit price but the result doesn't work.我试图按单价对一组产品进行排序,但结果不起作用。

typedef struct {
    int supply;
    int totalPrice;
    double unitPrice;
} Product;

int comparator(const void * a, const void * b) {
    return (*(Product*) b).unitPrice - (*(Product*) a).unitPrice;
}

int main() {
    Product m[3] = {
        {18, 75, 4.17},
        {15, 72, 4.80},
        {10, 45, 4.50}
    };
    qsort(m, 3, sizeof(Product), comparator);
    for (int i = 0; i < 3; i++) {
        printf("unitPrice=%f\n", m[i].unitPrice);
    }
}

comparator is broken. comparator坏了。 It subtracts two double values and returns an int .它减去两个double值并返回一个int Any fraction in the subtraction result is lost, so numbers less than one unit apart will be considered equal.减法结果中的任何分数都会丢失,因此相隔小于一个单位的数字将被视为相等。

Fix it to return a non-zero number if the items differ.如果项目不同,请修复它以返回非零数字。

Returning a double value from a function which returns int type value, will result in implicit conversion of double to int and the fractional part will be discarded from returned value.从返回int类型值的 function 返回一个double值,将导致doubleint的隐式转换,并且小数部分将从返回值中丢弃。

If you are using gcc compiler, try compiling with -Wconversion option, the compiler will give warning:如果您使用的是gcc编译器,请尝试使用-Wconversion选项进行编译,编译器会给出警告:

 warning: implicit conversion turns floating-point number into integer: 'double' to 'int' [-Wfloat-conversion]
    return (*(Product*) b).unitPrice - (*(Product*) a).unitPrice;
    ~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.

You can do:你可以做:

int comparator(const void * a, const void * b) {
    double first = (*(Product*) a).unitPrice;
    double second = (*(Product*) b).unitPrice;

    if (second > first) {
        return 1;
    } else if (second < first) {
        return -1;
    }
    return 0; // second == first
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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