为什么std :: accumulate函数显示向量< double&gt ;?的错误和 [英] Why is the std::accumulate function showing the wrong sum of a vector<double>?

查看:226
本文介绍了为什么std :: accumulate函数显示向量< double&gt ;?的错误和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码添加向量的所有元素

#include<iostream>
#include<algorithm>
#include<numeric>
#include<vector>
using namespace std;
int main(void)
{

   std::vector<double> V;
   V.push_back(1.2);
   V.push_back(3.6);
   V.push_back(5.6);
   double sum = accumulate(V.begin(),V.end(),0);

   cout << "The sum of the elements of the vector V is " << sum << endl;
   return 0;
}



当我在Windows上编译Cygwin并运行它时,

When I compile this on Cygwin on Windows and run it, I get the output at the terminal as


向量V的元素总和为9

The sum of the elements of the vector V is 9

accumulate 函数似乎将所有数字四舍五入并将它们相加,这将解释答案。

The accumulate function seems to be rounding down all the numbers and adding them up, which would explain the answer.

这是Cygwin g ++编译器出了问题,或者我错误地解释了 accumulate 函数添加了一个向量 double s?

Is this something wrong with the Cygwin g++ compiler, or my misinterpretation of the accumulate function for adding up a vector of doubles?

推荐答案

std :: accumulate 声明为:

template <typename InputIt, typename T>
T accumulate(InputIt first, InputIt last, T init);

std :: accumulate的第二个模板参数 0 的类型为 int ,所以推导为 int 。传递double,如 0.0

The second template argument to std::accumulate is deduced as int because 0 is of type int. Pass a double instead, like 0.0.

这篇关于为什么std :: accumulate函数显示向量&lt; double&gt ;?的错误和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆