在 c 中查找数组中位数时出现问题

问题描述 投票:0回答:1

我试图从 c 中的数据数组中找到中位数,但每次尝试时,即使数组中只有一个零,我也会得到零,数组在归入函数之前已排序。数组数据有效,因为我可以正确计算平均值和总和。

这是我的功能:

//The array is sorted prior to this
//count is the amount of values in the array

double median(int64_t *array)
{
        double q2;
        int64_t pos, pos1;
        if (count % 2 == 0) 
        {
                //even
                pos = count / 2;
                pos1 = (count + 2) / 2;
                q2 = (array[pos] + array[pos1]) / 2;
        }
        else
        {
                //odd
                pos = (count + 1) / 2;
                q2 = array[pos];
        }
        return q2;
}
c math
1个回答
0
投票

你似乎错过了数组索引从零开始。

如果您有一个包含两个元素的数组,则要使用的索引是 0 和 1。

然而,你的计算是:

// count is 2
pos = count / 2;  ---> 2/2 ---> 1
pos1 = (count + 2) / 2;  ---> (2 + 2)/2 ---> 4/2 ---> 2

所以你使用的是 1 和 2,而不是 0 和 1。

对于奇数计数值也存在同样的问题。

还有

q2 = (array[pos] + array[pos1]) / 2;

是整数除法,因此会丢失小数。

q2 = (array[pos] + array[pos1]) / 2.0;
© www.soinside.com 2019 - 2024. All rights reserved.