gpt4 book ai didi

c - qsort 不适用于双数组

转载 作者:太空宇宙 更新时间:2023-11-04 05:10:40 25 4
gpt4 key购买 nike

我尝试使用 qsort 对 double 值数组进行排序,但它似乎不起作用。不知道这里出了什么问题??

#include <stdio.h>
#include <stdlib.h>
static double compare (const void * a, const void * b)
{
if (*(double*)a > *(double*)b) return 1;
else if (*(double*)a < *(double*)b) return -1;
else return 0;
}

int main() {

int idx;
double* sum_least_square_err;

sum_least_square_err = (double*) malloc (2500*2500*sizeof(double));

sum_least_square_err[0] = 0.642;
sum_least_square_err[1] = 0.236;
sum_least_square_err[2] = 0.946;
idx = 3;

qsort(sum_least_square_err, idx, sizeof(sum_least_square_err), compare);

int i;
for (i=0; i<idx; i++){
fprintf(stderr,"sum_least_square_err[%d] = %.3f\n", i, sum_least_square_err[i]);
}
fprintf(stderr,"MAEE = %.3f\n", sum_least_square_err[idx/2]);

free(sum_least_square_err);
}

结果:

sum_least_square_err[0] = 0.642

sum_least_square_err[1] = 0.236

sum_least_square_err[2] = 0.946

MAEE = 0.236

最佳答案

改变:

static double compare (const void * a, const void * b)

到:

static int compare (const void * a, const void * b)

和改变:

qsort(sum_least_square_err, idx, sizeof(sum_least_square_err), compare);

到:

qsort(sum_least_square_err, idx, sizeof(sum_least_square_err[0]), compare);

注意:您应该已经收到关于第一个错误的适当编译器警告 - 您是否使用 gcc -Wall 或等效项进行编译,如果是,您是否注意到编译器警告? (如果没有,请接受提示,让编译器在将来为您捕获此类问题。)

关于c - qsort 不适用于双数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11931547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com