数组的平均分数

时间:2014-02-16 15:18:37

标签: c++ arrays function

我需要平均一个数组的分数。我在书中找到的所有内容都说明了你是如何做到这一点的。 “+ =”处有一个错误,表示“No operator”+ =“匹配这些操作数。”不知道我做错了什么......

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

5 个答案:

答案 0 :(得分:3)

score是一个std::string的数组。您不能使用字符串执行算术运算。 要做你想做的事,你必须在之前将它们转换成双打:

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

答案 1 :(得分:1)

分数是一个字符串数组,你需要一个数组(可能是整数)

答案 2 :(得分:1)

目前尚不清楚为什么要将得分保持在std::string的数组中。在算术运算中,您不能使用std::string类型的对象。您需要将std :: string类型的对象转换为某种算术类型,例如转换为int

例如

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

此外,您的函数具有未定义的行为,因为它不返回任何内容,并且函数的第三个参数是不必要的。而你忘了初始化变量总数。

我会按照以下方式编写函数

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 );
}

在主要内容中可以称为

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

您可以使用标头std::accumulate中声明的标准算法<numeric>来代替循环。例如

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

答案 3 :(得分:0)

您无法添加字符串元素。您必须更改参数的类型,或者您可以尝试将字符串转换为双精度

答案 4 :(得分:0)

doublestd::string转换外,如果您想了解有关数据的更多统计信息功能,我建议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;
}
相关问题