C ++ averages calculation

I have to show two decimal places on average. Right now it is rounded to the nearest number and shows zeros when there is a different amount for tenths and hundredths in the calculated amount. Probably something very simple. I thought a double declaration would allow this to show the correct calculation.

double CalculateAverageScore(int score[],int numPlayers, double averageScore)
{
    double total = 0;
    for (int i = 0; i < numPlayers; i++)
    {
        total += score[i];
    }
    averageScore = total / numPlayers;
    cout << fixed << showpoint << setprecision(2);
    cout << "\nAverage Score: " << averageScore << endl;
    return averageScore;
}
+3
source share
2 answers

Your solution should work as shown in your example.

double total = 0;
// ...
averageScore = total / numPlayers; // Result of division is of type double.

Here you divide a doubleby int, and the result should be double. Thus, no cast is required.

Some other problems:

  • You specified a parameter scoreas int*, which allows the client to pass a null value (and you do not check this).
  • numPlayers int, , std::size_t.
  • averageScore , . .
  • const-correctness, .. const, .

score int[N], . . :.

template <const std::size_t N>
double average(const int (&score)[N]) {
    return static_cast<double>(std::accumulate(std::begin(score), std::end(score), 0)) / N;
}

:

int score[5] = { 2, 2, 3, 4, 5};
std::cout << std::fixed << std::showpoint << std::setprecision(2);
std::cout << average(score) << std::endl; // Outputs 3.20

score, . std::array.

+1
averageScore = total / numPlayers;
                    ^^^
          integer division

:

averageScore = static_cast< double>( total) / numPlayers;
                  ^^^
               explicit cast

, double int, double, .


, , ,

double CalculateAverageScore(int score[],int numPlayers)
{
    //...
    double averageScore = total / numPlayers;
    return averageScore;
}

averageScore , :

double CalculateAverageScore(int score[],int numPlayers, double averageScore)
{
    double total = 0.0;
    //...
    averageScore = total / numPlayers;
                 ^
           forget initial value, so it was useless
           == no need to pass averageScore as argument
    //....
} 
+5

All Articles