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

Calculating averages in another method C++

本文关键字:平均值 计算 方法 另一种 C++      更新时间:2023-10-16

我将平均方法与main分开,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
}

如果你真的想将一个 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();
}

现在我们终于知道了真正的分配:

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

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