c - 使用 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);
}
}
解决方案
comparator
被打破。它减去两个double
值并返回一个int
. 减法结果中的任何分数都会丢失,因此相隔小于一个单位的数字将被视为相等。
如果项目不同,请修复它以返回非零数字。
推荐阅读
- php - 在实时服务器上的 phpmyadmin 上运行任何查询时出错。但是当我在 adminer.php 上运行它时,它正在执行
- css - 如果两个同级内联元素用垂直对齐标记,那么作为基线的字体是什么?
- android - 为什么我在开发中没有无限的 Firebase 资源?
- javascript - 简单的 websocket 库(这在通话中丢失)
- java - 如何在 HSSFSheet 中自动调整合并行的高度?
- reactjs - 从父级调用功能组件的子级方法
- python - 如何计算元组中的对数,以使对中的两个元素都是偶数?
- javascript - 我的 discord.js 命令无法正常工作
- swift - 如何在动态uitextview下添加固定视图?
- javascript - 如何使用 vue js 过滤日期范围?