写一个函数来求整数向量的中值

Writing a function to find the median, of a vector of ints

本文关键字:整数 向量 函数 一个      更新时间:2023-10-16

我正试图编写第二个函数来计算主函数中的整数向量。我的向量是这样设置的

int inputinfo;
cout << "nPlease enter in scores: ";
cout << "nEnd your input with ctrl-zn";
vector<int> scores;
    while (cin >> inputinfo)
    {
        scores.push_back(inputinfo);
    }

这是我的中位数方程(我不确定是正确的)。我想为中位数创建一个函数,然后将其调用回主函数以查找向量的中位数。

  double median;
  size_t size = scores.size();
  sort(scores.begin(), scores.end());
  if (size  % TWO == 0)
  {
      median = (scores[size / 2 - 1] + scores[size / 2]) / 2;
  }
  else 
  {
      median = scores[size / 2];
  }

谢谢你的帮助

如果向量中没有数字或只有一个数字,检查代码是否失败。您可以使用

修复此问题。
if (size==0) throw "Vector empty";
if (size==1) return scores[0];
在if (size % TWO == 0)行前插入

简单概括一下:中位数是指排序列表的中间项,对吧?所以你搜索

//your array has a even size, so you want the middle of it
if (size  % TWO == 0)
{
median = scores[size / 2 - 1];
}
// your array has a odd size, so you average 
else 
{
median = (scores[size / 2 - 1] + scores[size / 2]) / 2;
}