数组的平均分数

Average scores from an array

本文关键字:平均分 数组      更新时间:2023-10-16

我需要从数组中平均分数。我在书中能找到的只是说这就是你的做法。"+="处有一个错误,指出"没有运算符"+="与这些操作数匹配。不知道我做错了什么...

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

score 是一个std::string数组。不能对字符串执行算术运算。要做你想做的事,你必须在以下之前将它们转换为双精度:

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

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

目前尚不清楚为什么您将分数保持在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;

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

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

除了doublestd::string转换之外,如果您想获得更多有关数据的统计信息功能,我会推荐 升压累加器

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

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