2016-04-23 45 views
0

我將main方法與main方法分開,兩位同學都在調用方法,但我不太確定如何通過這種方式計算平均值,有什麼想法?以另一種方法計算平均值C++

平均做兩件事。它計算學生分數的平均值,將整數平均值放入最終元素中,從而替換負數,然後返回它在數組中找到的實際測試分數。數組中的哨兵是負數。

這裏是我的代碼

#include <iostream> 
using namespace std; 

double average(int array[]); // function declaration (prototype) 

int main() 
{ 
    int lazlo[] = {90, 80, 85, 75, 65, -10}; 
    int pietra[] = { 100, 89, 83, 96, 98, 72, 78, -1}; 
    int num; 

    num = average(lazlo); 
    cout << "lazlo took " << num << "tests. Average: " << lazlo[ num ] << endl; 

    num = average(pietra); 
    cout << "pietra took " << num << "test. Average: " << pietra[ num ] << endl; 

} 

double average(int array[]) 
{ 
    // Average code 

} 
+2

你'average'功能已經不知道有多少項目有在數組中。這有助於你找出遺漏的東西嗎? – PaulMcKenzie

回答

0

現在我們終於知道真正的分配:

「平均做了兩件事它計算學生的分數的平均值,在一些地方的整數平均最終元素因此替換了負數,然後返回它在陣列中找到的實際測試分數。陣列中的哨兵是一個負數「

double average(int array[]) 
{ 
    int i = 0; 
    int Total = 0; 
    while (array[i] >= 0)  //Keep adding to total and increase i until negative value found. 
     Total += array[i++]; 

    array[i] = Total/i; 
    return i;     //Weird to return a double for this, but if that is the assignment... 
} 
0

如果你真的想通過一個C數組作爲唯一的參數爲average()功能,必須使用模板來推斷它的大小:

#include <numeric> 
#include <iostream> 

using namespace std; 

template <size_t N> 
size_t count(int (&array)[N]) 
{ 
    return N; 
} 

template <size_t N> 
double average(int (&array)[N]) 
{ 
    return std::accumulate(array, array + N, 0.0)/N; 
} 

int main() 
{ 
    int lazlo[] = {90, 80, 85, 75, 65, -10}; 

    double num = average(lazlo); 
    cout << "lazlo took " << count(lazlo) << " tests. Average: " << average(lazlo) << endl; 
} 

當然,因爲這是C++,你可能使用std::vectorstd::array存儲分數會更好,在這種情況下,你可以這樣做:

double average(const std::vector<int>& array) 
{ 
    return std::accumulate(array.begin(), array.end(), 0.0)/array.size(); 
} 
+0

不幸的是,我只能編輯平均的方法和原型,而不是整個程序@JohnZwinck – HoodCoolege

+0

@HoodCoolege:沒問題 - 你可以將我的第一個'average'版本插入到你現有的程序中。它的調用方式完全相同。 –