c - 求向量中位数的函数?
问题描述
我正在尝试编写一个函数来查找给定数组的中位数。我有一个问题,当它开始时它没有为偶数或奇数输出正确的值。然而,排序的输入工作。有人看到我的代码有什么问题吗?谢谢!
double vect_median( const double x[], unsigned length)
{
double ordered[LENGTH] = {0}; //new vector to hold the ordered items, use of {} to accommodate larger sizes
int temp = 0; //var to hold the value of an item for re-arrangement
float result = 0;
for (size_t k = 0; k < length; ++k)
{
ordered[k] = x[k];
}
for (size_t i = 1; i < length; ++i) //loops to order the values of the vector, start at 1 because length != 0
{
for (size_t n = 0; n < (length - 1); ++n) //loop to indivudally check each value
{
if (ordered[n] > ordered[n + 1]) //if first is greater than second
{
temp = ordered[n]; //switch the order of the two values
ordered[i] = ordered[i + 1];
ordered[i+1] = temp;
}
}
//once a value is switched, the loops breaks and the outside loop runs it again LENGTH times
if(length % 2 == 1)//if odd
{
result = ordered[LENGTH/2]; //return the val in the middle of the dataset
}
else
{
result = (ordered[LENGTH/2] + ordered[LENGTH/2 - 1])/2;
}
}
return(result);
}
解决方案
这是错误的,因为它i
在根据以下内容做出决定后使用n
:
if (ordered[n] > ordered[n + 1]) //if first is greater than second
{
temp = ordered[n]; //switch the order of the two values
ordered[i] = ordered[i + 1];
ordered[i+1] = temp;
}
推荐阅读
- reactjs - 错误:元素类型无效:需要一个字符串(用于内置组件)或一个类/函数,以防服务器端使用 react 渲染
- reactjs - 材质 ui AppBar 文本颜色更改为白色/返回功能
- jsp - 运行 JSP 页面时出现 Tomcat 错误:源服务器未找到目标资源的当前表示
- ios - 在 SwiftUI 中更改 UITableViewCell 背景颜色
- c - 从网络服务器 C/C++ 发送的额外字符
- ccxt - 如何调用 ccxt 使用 bitget DEMO 货币 'cmt_btcsusdt'
- amazon-web-services - AWS ec2 实例无法在内部 ssh
- javascript - 如何将空字符串数组转换为空数组?
- android - 如何在TOP制作吐司秀?
- javascript - 网页中的文件查看器