我有一个任务来读取文件并输出平均考试成绩。
这很简单,但我不喜欢平均的方式。
average = (test1 + test2 + test3 + test4 + test5) / 5.0;
有没有办法让它除以考试成绩的数量?我在书中或从谷歌找不到这样的东西。像
average = (test + test + test + test) / ntests;
如果你有一个向量或数组中的值,只需使用std::accumulate
从<numeric>
:
std::vector<double> vec;
// ... fill vec with values (do not use 0; use 0.0)
double average = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();
步骤 1.通过迭代(如果你想做)或递归(如果你想勇敢)将所有测试分数放入数组(如果你想要简单和速度)或链表(如果你想要灵活性,但速度慢)
步骤 2。迭代数组 / 列表,直到到达终点;添加每个单元格 / 节点的内容。
步骤 3。从第一个变量中取出总和,然后将其除以跟踪您所在位置的第二个变量。这将产生平均值。
想知道,为什么没有人提到boost::accumulators
。它不是已经发布的解决方案中最短的,而是可以更容易地扩展为更一般的统计值。像标准偏差或更高的矩。
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <algorithm>
#include <vector>
double mean(const std::vector<double>& values) {
namespace bo = boost::accumulators;
if (values.empty()) return 0.;
bo::accumulator_set<double, bo::stats<bo::tag::mean>> acc;
acc=std::for_each(values.begin(), values.end(), acc);
return bo::mean(acc);
}
int main()
{
std::vector<double> test = { 2.,6.,4.,7. };
std::cout << "Mean: " << mean(test) << std::endl;
std::cout << "Mean: " << mean({}) << std::endl;
return 0;
}
这是我通过指定 lambda 函数来获取容器元素的平均值,以获取每个值,然后加起来:
template <typename ForwardIterator, typename F>
double inline averageOf (ForwardIterator first, ForwardIterator last, F function) {
std::vector<typename std::result_of<F(typename ForwardIterator::value_type)>::type> values;
while (first != last) {
values.emplace_back (function(*first));
++first;
}
return static_cast<double>(std::accumulate (values.begin(), values.end(), 0)) / values.size();
}
我测试它的客户端代码像
const std::list<CharmedObserver*> devotees =
charmer->getState<CharmerStateBase>(CHARMER)->getDevotees();
const int averageHitPointsOfDevotees = averageOf (devotees.begin(), devotees.end(),
[](const CharmedObserver* x)->int {return x->getCharmedBeing()->getHitPoints();});
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(61条)