0

単純な配列を関数に渡して平均を計算しようとしています。

int main()
{
    int n = 0; // the number of grades in the array
    double *a; // the array of grades

    cout << "Enter number of scores: ";
    cin >> n;

    a = new double[n]; // the array of grades set 
                       // to the size of the user input

    cout << "Enter scores separated by blanks: ";
    for(int i=0; i<n; i++)
    {
        cin >> a[i];
    }

    computeMean(a, n);
}

double computeMean (double values[ ], int n)
{
    double sum;
    double mean = 0;
    mean += (*values/n);
    return mean;
}

現在、コードは最後に入力された数値の平均のみを取っています。

4

3 に答える 3

5

関数にループはありません。次のようになります。

double sum = 0;
for (int i = 0; i != n; ++i)
  sum += values[i];

return sum / n;

現在のバージョンでは最後の番号しか使用されないことに驚いています。はと同じであるため、最初の番号のみを使用する必要があります。*valuesvalues[0]

より良い解決策は慣用的なC++を使用します:

return std::accumulate(values, values + n, 0.0) / n;
于 2011-09-08T22:35:29.790 に答える
2

std::accumulateトリックを行う必要があります。

#include <numeric>

double computeMean (double values[ ], int n) {
    return std::accumulate( values, values + n, 0. ) / n;
}
于 2011-09-08T22:36:32.583 に答える
0

これは宿題の質問ですか?

配列内のすべての値をステップスルーする必要があります。現在、配列の最初の数値をアイテムの数で割った値を出力しています。

于 2011-09-08T22:36:49.200 に答える