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

使用qsort对C中的结构数组进行排序,c,qsort,C,Qsort,我试图按单价对一系列产品进行排序,但结果不起作用 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() { Pro

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

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);
    }
}
typedef结构{
国际供应;
国际总价格;
双倍单价;
}产品;
int比较器(常量无效*a,常量无效*b){
退货(*(产品*)b)。单价-(*(产品*)a)。单价;
}
int main(){
乘积m[3]={
{18, 75, 4.17},
{15, 72, 4.80},
{10, 45, 4.50}
};
qsort(m,3,sizeof(产品),比较器);
对于(int i=0;i<3;i++){
printf(“单价=%f\n”,m[i]。单价);
}
}

比较器
损坏。它减去两个
double
值并返回一个
int
。减法结果中的任何分数都将丢失,因此相距小于一个单位的数字将被视为相等


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

比较器已损坏。它减去两个
double
值并返回一个
int
。减法结果中的任何分数都将丢失,因此相距小于一个单位的数字将被视为相等


如果项目不同,请将其修复为返回非零数字。

从返回
int
类型值的函数返回
double
值,将导致
double
隐式转换为
int
,并且从返回值中丢弃小数部分

如果您使用的是
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.
你可以做:

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
}
int比较器(常量无效*a,常量无效*b){
双首=(*(产品*)a)。单价;
双秒=(*(产品*)b)。单价;
如果(第二次>第一次){
返回1;
}否则如果(第二次<第一次){
返回-1;
}
返回0;//第二个==第一个
}

从返回
int
类型值的函数返回
double
值,将导致
double
int
的隐式转换,并且从返回值中丢弃小数部分

如果您使用的是
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.
你可以做:

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
}
int比较器(常量无效*a,常量无效*b){
双首=(*(产品*)a)。单价;
双秒=(*(产品*)b)。单价;
如果(第二次>第一次){
返回1;
}否则如果(第二次<第一次){
返回-1;
}
返回0;//第二个==第一个
}

编辑您的问题以同时显示输出会很有帮助。编辑您的问题以同时显示输出会很有帮助。在没有任何公差的情况下比较相等的浮点值(此处隐式完成)总是一种代码味道。我将定义类似于
staticconstdoubletolerance=0.005(第二个>第一个+公差)
(第二个<第一个-公差)
。在没有任何公差的情况下比较相等的浮点值(此处隐式完成)总是一种代码味道。我将定义类似于
staticconstdoubletolerance=0.005然后
(第二次>第一次+公差)
(第二次<第一次-公差)