我正在爲我的C++類創建一個程序,其目標是創建一個函數來查找矢量的最高,最低,平均值和中值,並將其作爲結構返回。我已經有了所有的函數,但是我遇到的問題是我的平均函數沒有爲平均值返回正確的值。平均功能不能正常工作
#include "std_lib_facilities_4.h"
struct VALUES{
int lowest;
int highest;
int median;
int mean;
};
VALUES actions(vector <int> a){
VALUES b;
int lowest = 100;
int highest = 0;
int total;
int median;
int mean;
for(int i = 0; i<a.size(); i++){
if(a[i]<lowest){
lowest = a[i];
}
if(a[i]>highest){
highest = a[i];
}
total = total + a[i];
}
median = a[a.size()/2];
mean = total/11;
b.lowest = lowest;
b.highest = highest;
b.median = median;
b.mean = mean;
return b;
}
int main(){
vector <int> original;
for(int i = 0; i<11; i++){
original.push_back(i);
}
//actions(original);
VALUES ending;
ending = actions(original);
cout<< "Lowest " << ending.lowest<< "\n";
cout<< "Highest " << ending.highest<< "\n";
cout<< "Median " <<ending.median<< "\n";
cout<< "Mean " <<ending.mean<< "\n";
}
我已經多次查找過這個小錯誤,但是我一直找不到。答案在運行程序時顯示2983。
如果存在奇數個值,則中值是排序值列表的「中值」中的值,並且這兩個中間值的平均值是奇數個值。如果你有11個值,你可以在這次提供列表排序。 – Marichyasana 2015-02-08 06:38:45