我是一名编程学生,对于我正在进行的一个项目,我必须做的事情之一是计算 int 值向量的中值.我将仅使用 STL 中的排序函数和向量成员函数(例如 .begin()
、.end()
和 .size>)来执行此操作()
.
I'm a programming student, and for a project I'm working on, on of the things I have to do is compute the median value of a vector of int values. I'm to do this using only the sort function from the STL and vector member functions such as .begin()
, .end()
, and .size()
.
我还应该确保我找到中位数,无论向量的值是奇数还是偶数.
I'm also supposed to make sure I find the median whether the vector has an odd number of values or an even number of values.
我卡住,下面是我的尝试.那么我哪里出错了?如果您愿意给我一些指示或资源以朝着正确的方向前进,我将不胜感激.
And I'm Stuck, below I have included my attempt. So where am I going wrong? I would appreciate if you would be willing to give me some pointers or resources to get going in the right direction.
代码:
int CalcMHWScore(const vector<int>& hWScores)
{
const int DIVISOR = 2;
double median;
sort(hWScores.begin(), hWScores.end());
if ((hWScores.size() % DIVISOR) == 0)
{
median = ((hWScores.begin() + hWScores.size()) + (hWScores.begin() + (hWScores.size() + 1))) / DIVISOR);
}
else
{
median = ((hWScores.begin() + hWScores.size()) / DIVISOR)
}
return median;
}
你正在做一个额外的划分,总体上使它比需要的更复杂一些.此外,当 2 在上下文中实际上更有意义时,就没有必要创建 DIVISOR.
You are doing an extra division and overall making it a bit more complex than it needs to be. Also, there's no need to create a DIVISOR when 2 is actually more meaningful in context.
double CalcMHWScore(vector<int> scores)
{
size_t size = scores.size();
if (size == 0)
{
return 0; // Undefined, really.
}
else
{
sort(scores.begin(), scores.end());
if (size % 2 == 0)
{
return (scores[size / 2 - 1] + scores[size / 2]) / 2;
}
else
{
return scores[size / 2];
}
}
}
这篇关于计算存储在向量中的值的中位数 - C++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!