2009-07-10 122 views
1

我在計算最小值,最大值,平均值,中位數時在返回多個值時遇到了一些麻煩。我做的第一件事是傳遞引用參數,它工作 - 但我讀了創建一個結構或類是返回多個值的首選方法。試圖返回多個值

所以我嘗試了,我一直沒有得到好的結果。這是我到目前爲止。

#include "std_lib_facilities.h" 
struct maxv{ 
     int min_value; 
     int max_value; 
     double mean; 
     int median; 
}; 

maxv calculate(vector<int>& max) 
{ 

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

    min_value = max[0]; 

    int m = 0; 
    m = (max.size()-1); 
    max_value = max[m]; 

    for(int i = 0; i < max.size(); ++i) mean += max[i]; 
    mean = (mean/(max.size())); 

    int med = 0; 
    if((max.size())%2 == 0) median = 0; 
    else 
    { 
     med = (max.size())/2; 
     median = max[med]; 
     } 

} 

int main() 
{ 
    vector<int>numbers; 
    cout << "Input numbers. Press enter, 0, enter to finish.\n"; 
    int number; 
    while(number != 0){ 
       cin >> number; 
       numbers.push_back(number);} 
    vector<int>::iterator i = (numbers.end()-1); 
    numbers.erase(i); 
    maxv result = calculate(numbers); 
    cout << "MIN: " << result.min_value << endl; 
    cout << "MAX: " << result.max_value << endl; 
    cout << "MEAN: " << result.mean << endl; 
    cout << "MEDIAN: " << result.median << endl; 
    keep_window_open(); 
} 

顯然,在計算函數的變量是未申報。我只是不知道如何以正確的方式實現這個返回正確的值。到目前爲止,我已經試過了,我已經得到了非常有價值的解釋。任何幫助將不勝感激 - 謝謝。

P.S.我已經看過關於這個主題的其他線程,我仍然有點困惑,因爲在需要傳遞給calculate()的變量和maxv結構中的變量之間沒有真正的區別。

+0

爲什麼你不顯示完整的功能?中位數可能會錯誤計算,因爲您不會將均值初始化爲零。 – Dingo 2009-07-10 03:59:49

+0

很高興地說「這是我到目前爲止」。 – ChrisW 2009-07-10 04:16:13

回答

8

有三種方法可以做到這一點。

1)從計算函數返回一個MAXV實例

maxv calculate(vector<int>& max) 
{ 
    maxv rc; //return code 
    ... some calculations ... 
    ... initialize the instance which we are about to return ... 
    rc.min_value = something; 
    rc.max_value = something else; 
    ... return it ... 
    return rc; 
} 

2)通入一個MAXV例如通過參考

void calculate(vector<int>& max, maxv& rc) 
{ 
    ... some calculations ... 
    ... initialize the instance which we were passed as a parameter ... 
    rc.min_value = something; 
    rc.max_value = something else; 
} 

3)都說計算是MAXV結構的方法(或更好的構造函數)

struct maxv 
{ 
    int min_value; 
    int max_value; 
    double mean; 
    int median; 

    //constructor 
    maxv(vector<int>& max) 
    { 
     ... some calculations ... 
     ... initialize self (this instance) ... 
     this->min_value = something; 
     this->max_value = something else; 
    } 
};