数组的平均分数
Average scores from an array
我需要从数组中平均分数。我在书中能找到的只是说这就是你的做法。"+="处有一个错误,指出"没有运算符"+="与这些操作数匹配。不知道我做错了什么...
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 );
除了double
和std::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;
}
不能添加字符串的元素。您必须更改参数的类型,或者您可以尝试将字符串转换为双精度
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '