当我使用 add_card 运行添加卡时,在第七张卡上它应该对所有卡进行排序。但是当我运行这个时,我得到了一个半有序的结果。
>> require 'ext/straight_count' #=> true >> s = EV::StraightCount.new; s.add_card(5,0); s.add_card(8,1); s.add_card(12,2); s.add_card(14,3); s.add_card(12,4); s.add_card(3,5); s.add_card(5,6)
card: 12
card: 5
card: 12
card: 14
card: 8
card: 5
card: 3
我不认为 NUM2INT 有问题,因为当我无序打印数组时,它会按预期输出。
直.h
int *pCards, *pSortedCards;
int cCards[NUM_CARDS], cSortedCards[NUM_CARDS];
直.c
void Init_straight()
{
pCards = &cCards[0];
}
static VALUE
add_card(VALUE self, int rCardValue, int rCardIndex)
{
*(pCards + NUM2INT(rCardIndex)) = NUM2INT(rCardValue);
if (NUM2INT(rCardIndex) == 6)
check_for_straight();
return Qnil;
}
check_for_straight()
{
sort_by_value(pCards);
}
card_sort.c
int compare_card_values (const void *a, const void *b)
{
const double *da = (const double *) a;
const double *db = (const double *) b;
return (*da > *db) - (*da < *db);
}
void sort_by_value(int *pCards)
{
qsort(pCards, NUM_CARDS, sizeof(pCards[0]), compare_card_values);
}
最佳答案
即使数组包含 int
,您也会在 compare_card_values
中将卡片值转换为 double
。试试这个:
int compare_card_values (const void *a, const void *b)
{
const int *da = (const int *) a;
const int *db = (const int *) b;
return (*da > *db) - (*da < *db);
}
关于c - 为什么我的 qsort 结果不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6479431/