我正在尝试使用qsort()对结构中的价格进行排序。排序后,结构中的一个元素(测试)变为0.你能告诉我为什么以及如何解决它?
谢谢!
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int price;
int test;
int id;
} order;
order list[10];
int i = 0;
int compare (const void * a, const void * b)
{
order *orderA = (order *)a;
order *orderB = (order *)b;
return ( orderA->price - orderB->price );
}
int main ()
{
srand ( time(NULL) );
printf("Before sorting\n");
for(i=0; i<10; i++){
list[i].price = rand()%10;
list[i].test = rand()%10;
list[i].id = i;
printf ("Order id = %d Price = %d Test = %d\n",list[i].id, list[i].price, list[i].test);
}
printf("AFTER sorting\n");
int n;
qsort (list, 6, sizeof(order), compare);
for (n=0; n<10; n++)
printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test);
return 0;
}
输出为:
在分拣之前 订单ID = 0价格= 4测试= 2
订单ID = 1价格= 9测试= 3
订单ID = 2价格= 5测试= 0
订单ID = 3价格= 2测试= 8
订单ID = 4价格= 8测试= 5
订单ID = 5价格= 7测试= 4
订单ID = 6价格= 9测试= 3
订单ID = 7价格= 1测试= 1
订单ID = 8价格= 8测试= 4
订单ID = 9价格= 3测试= 3
分拣后 订单ID = 3价格= 2测试= 0
订单ID = 0价格= 4测试= 0
订单ID = 2价格= 5测试= 0
订单ID = 5价格= 7测试= 0
订单ID = 4价格= 8测试= 0
订单ID = 1价格= 9测试= 0
订单ID = 6价格= 9测试= 0
订单ID = 7价格= 1测试= 0
订单ID = 8价格= 8测试= 0
订单ID = 9价格= 3测试= 0
答案 0 :(得分:2)
排序后,更改
printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test);
到
printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[n].test);