读书人

STL 平均值出错为什么?该怎么处理

发布时间: 2012-03-08 13:30:13 作者: rapoo

STL 平均值出错,为什么?
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

template <typename RndIter>
double average(RndIter first ,RndIter last)
{
return accumulate(first,last,0.0)/(last-first);
}

int main()
{
vector <int> v(10,1);
partial_sum(v.begin(),v.end(),ostream_iterator <int> (cout, " "));

//partial_sum 算法可以用于生成从 1 到 N 的整数

cout < <endl;
cout < < "The average is " < <average(v.begin(),v.end()) < <endl;
return 0;
}


[解决办法]
没出错啊,十个 1 的平均值也是 1

如果你是想求 1 2 3 4 ... 9 的平均值的话 partial_sum(v.begin(),v.end(),ostream_iterator <int> (cout, " "));
改为
partial_sum(v.begin(),v.end(),v.begin());
[解决办法]
平均值没有错误啊,输出为1

读书人网 >C++

热点推荐