2014-02-16 145 views
0

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

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

你必须分析score'的'双打弦或浮动以便使用'+ ='。 – Netwave

+0

你不能将'std :: string'添加到'double'。 –

回答

3

scorestd::string秒的阵列。您不能使用字符串执行算术运算。 要做到你想要什么,你必须之前将它们转换为双打:

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

另外,for循环之前需要将'total'初始化为0。 –

1

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

0

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

+0

它可能不是必需的。有很多方法可以将字符串转换为整数或双精度。只需要检查蜇伤的有效性,如果它们是数字。 –

+0

你是对的我编辑它 – Rooxo

1

不清楚为什么要将分数保存在std::string的数组中。在算术运算中不得使用std::string类型的对象。你需要输入字符串的std ::的对象转换为某种类型的算术例如以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); 
0
double

除了和std::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; 
}