2013-01-20 38 views
1

我想写第二个函数来计算主函数中的整数向量。我的矢量是这样设置的。写一个函数来查找整数的位数

int inputinfo; 
cout << "\nPlease enter in scores: "; 
cout << "\nEnd your input with ctrl-z\n"; 
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]; 
    } 

感谢您的任何帮助。

+8

你问如何使和调用一个函数? – chris

+1

由于您的中位数是一个浮点数,您可能需要中位数=(分数[size/2 - 1] +分数[size/2])/2.0;避免截断。 – user515430

回答

2

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

if (size==0) throw "Vector empty"; 
if (size==1) return scores[0]; 

在if(size%TWO == 0)行之前。

+6

没有必要为1的大小做一个特殊情况。 –

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