计算向量中存储的值的中值 - C ++? [英] Compute Median of Values Stored In Vector - C++?

查看:134
本文介绍了计算向量中存储的值的中值 - C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个编程学生,对于我正在开发的项目,我需要做的是计算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().

我也应该确保

而且我停滞,我已经包含了这个值我的尝试。所以我在哪里错了?如果您愿意给我一些指导或资源,以朝着正确的方向前进,我将非常感激。

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;
}

谢谢! >

Thanks!!

推荐答案

你正在做一个额外的分割,使得它比需要的更复杂一些。此外,当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)
{
  double median;
  size_t size = scores.size();

  sort(scores.begin(), scores.end());

  if (size  % 2 == 0)
  {
      median = (scores[size / 2 - 1] + scores[size / 2]) / 2;
  }
  else 
  {
      median = scores[size / 2];
  }

  return median;
}

这篇关于计算向量中存储的值的中值 - C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆