首页 > 解决方案 > 使用 qsort 对 C 中的结构数组进行排序

问题描述

我试图按单价对一组产品进行排序,但结果不起作用。

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

标签: cqsort

解决方案


comparator被打破。它减去两个double值并返回一个int. 减法结果中的任何分数都会丢失,因此相隔小于一个单位的数字将被视为相等。

如果项目不同,请修复它以返回非零数字。


推荐阅读