写一个函数来求整数向量的中值
Writing a function to find the median, of a vector of ints
我正试图编写第二个函数来计算主函数中的整数向量。我的向量是这样设置的
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;
}
相关文章:
- C++ 如何比较n个排序的整数向量以找到互元素?
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 如何将整数向量插入到键中,标准::映射的值
- 整数对的向量转化为整数向量的向量
- 如何组合两个整数向量
- C++中整数向量的序列化/反序列化
- 我无法在C++中启动整数向量
- 根据偶数值对整数向量进行排序
- 从整数向量向量搜索整数向量的最佳算法
- 如何将数字转换为整数向量?
- 我需要声明一个包含整数向量的 4x4 矩阵
- 基于整数向量执行位排列的有效方法?
- 将整数向量转换为字节数组向量,然后调用每个字节数组
- 如何将整数向量转换为 2 位十六进制并按顺序添加到 c 字符串?
- 为什么从右值整数向量的元素中推导 decltype(auto) 的类型是 int&?
- 将字符串转换为整数向量
- 尝试创建随机整数向量时的OpenMPI编译器错误
- 整数向量可以创建的整数项的最大数量
- 初始化和显示整数向量时出现意外结果