首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-03-08 
STL 平均值出错,为什么?#include iostream#include vector#include algorithm#include numericusi

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

热点排行