用另一种方法C ++计算平均值

时间:2016-04-23 02:40:35

标签: c++ average

我将普通方法与main分开,两个主要学生都调用了方法,但我不太确定如何通过这样做来计算平均值,任何想法?

平均做两件事。它计算学生分数的平均值,将整数平均值放在最终元素中,从而替换负数,然后返回它在数组中找到的实际测试分数。数组中的标记是负数。

这是我的代码

#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 个答案:

答案 0 :(得分: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...
}

答案 1 :(得分: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();
}