Zach707
Zach707

Reputation: 35

Average scores from an array

I need to average scores from an array. All I can find in the book says this is how you do it. There is an error at the "+=" that states, "No operator "+=" matches these operands." Don't know what I'm doing wrong...

double calculateAverageScore(string score[],int numPlayers, double averageScore)
{
double total;
for (int i = 0; i < numPlayers; i++)
{
    total += score[i];
}
averageScore = total / numPlayers;
    cout << "Average: " << averageScore << endl;
}

Upvotes: 0

Views: 166

Answers (5)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

It is not clear why you keep scores in an array of std::string. You may not use objects of type std::string in arithmetical operations. You need to convert an object of type std::string to some arithmetical type for example to int

For example

total += std::stoi( score[i] );

Also your function has undefined behaviour because it returns nothing and the third parameter of the function is unnecessary. And you forgot to initialize variable total.

I would write the function the following way

double calculateAverageScore( const string score[], int numPlayers )
{
   double total = 0.0;

   for ( int i = 0; i < numPlayers; i++ )
   {
      total += stoi( score[i] );
   }

   return (  numPlayers == 0 ? 0.0 : total / numPlayers );
}

and in main it could be called as

cout << "Average: " << calculateAverageScore( YourArrayOfStrings, NumberOfElements ) << endl;

Instead of the loop you could use standard algorithm std::accumulate declared in header <numeric>. For example

double total = std::accumulate( score, score + numPlayers, 0 );

Upvotes: 1

Rooxo
Rooxo

Reputation: 118

You can't add elements of an string. You have to change the type of your parameter or you can try to convert the string to an double

Upvotes: 0

gongzhitaao
gongzhitaao

Reputation: 6682

Apart from double and std::string conversion, if you'd like more stats features about your data, I would recommed Boost Accumulator

#include <algorithm>
#include <iostream>
#include <vector>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
using namespace boost::accumulators;

int main()
{
  std::vector<double> data = {1.2, 2.3, 3.4, 4.5};

  accumulator_set<double, stats<tag::mean> > acc;

  acc = std::for_each(data.begin(), data.end(), acc);

  std::cout << "Mean:   " << mean(acc) << std::endl;
  return 0;
}

Upvotes: 0

Tim Bergel
Tim Bergel

Reputation: 495

Score is an array of strings, you need an array of numbers (integers probably)

Upvotes: 1

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11502

score is an array of std::strings. You can't perform arithmetic operations with strings. To do what you desire, you have to convert them to doubles before:

total += std::stod(score[i]);

Upvotes: 3

Related Questions