tom*_*136 6 c arrays sorting double
if I have an array
double i[5] = {1.023, 1.22, 1.56, 2, 5, 3.331};
Run Code Online (Sandbox Code Playgroud)
how do i sort the values so that they look like this:
double i[5] = {1.023, 1.22, 1.56, 2, 3.331, 5};
Run Code Online (Sandbox Code Playgroud)
i've tried qsort() with no luck, after trying some examples, i came up with:
qsort(i, 5, sizeof(double), sort);
int sort(const void *x, const void *y)
{
return (*(double*)x - *(double*)y);
}
Run Code Online (Sandbox Code Playgroud)
with => error: incompatible type for argument 1
not sorting the array.....
NPE*_*NPE 13
第一个参数qsort是指向要排序的数组的开头的指针.代替
qsort(i[5], 5, sizeof(double), sort);
Run Code Online (Sandbox Code Playgroud)
它应该读
qsort(i, 5, sizeof(double), sort);
Run Code Online (Sandbox Code Playgroud)
进一步的观察:
i初始化程序的长度不正确(i有五个元素,但初始化程序有六个).qsort呼叫中是为了以后遇到麻烦.i"最常用于循环计数器等.sort令人困惑.1.1和1.2.还要考虑如果两个值之间的差异不适合,会发生什么int.我会像这样重写你的整个例子:
double arr[] = {1.023, 1.22, 1.56, 2, 5, 3.331};
int cmp(const void *x, const void *y)
{
double xx = *(double*)x, yy = *(double*)y;
if (xx < yy) return -1;
if (xx > yy) return 1;
return 0;
}
int main() {
qsort(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0]), cmp);
}
Run Code Online (Sandbox Code Playgroud)
注意,上面的比较函数仍然没有正确处理NaNs; 我把它作为练习让读者解决这个问题.
| 归档时间: |
|
| 查看次数: |
9715 次 |
| 最近记录: |