为什么std :: accumulate函数显示向量<double>的错误总和?

smi*_*dha 19 c++ vector accumulate

考虑以下代码来添加a的所有元素vector:

#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;
}
Run Code Online (Sandbox Code Playgroud)

当我在Windows上的Cygwin上编译它并运行它时,我得到终端的输出为

矢量V的元素之和为9

该accumulate功能似乎是将所有数字四舍五入并加起来,这可以解释答案.

这是什么问题Cygwin的G ++编译器,或我的误解accumulate添加了功能vector的doubleS'

rig*_*old 32

std::accumulate 声明如下:

template <typename InputIt, typename T>
T accumulate(InputIt first, InputIt last, T init);
Run Code Online (Sandbox Code Playgroud)

第二个模板参数std::accumulate推断为int因为0是类型int.通过双,而不是0.0.

  • 噢亲爱的!这对我来说似乎是一种错误.从观察向量元素的本质来推断类型是不是更合乎逻辑?这种定义累积的方式有用吗? (4认同)

小智 6

更改0到0.0.然后它10.4适合我.虽然容器是double的,但类型推导是int因为传递给的初始参数std::accumulate.因此,容器被赋值int.


Kar*_*oll 5

从std :: accumulate函数返回的值是一个整数,而不是double,因为:

double sum = accumulate(V.begin(), V.end(), 0);
//                                          ^-- Integer!
Run Code Online (Sandbox Code Playgroud)

由C++编译器完成的模板参数推断使得accumulate函数的返回类型与init参数相同,在您的情况下,该参数是整数.因此,返回值将四舍五入为最接近的整数.然后返回值在被赋值时被隐式地转换回double sum.

要解决此问题,您可以简单地将零作为double(即0.0)传递.