Consider the following code for adding all the elements of 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;
}
When I compile this on Cygwin on Windows and run it, I get the output at the terminal as
The sum of the elements of the vector V is 9
The accumulate
function seems to be rounding down all the numbers and adding them up, which would explain the answer.
Is this something wrong with the Cygwin g++ compiler, or my misinterpretation of the accumulate
function for adding up a vector
of double
s?
Change
0
to0.0
. It then gets10.4
for me. While the container is double, the type deduction isint
because of the initial argument passed tostd::accumulate
. Therefore, the container is assignedint
values.std::accumulate
is declared as such:The second template argument to
std::accumulate
is deduced asint
because0
is of typeint
. Pass a double instead, like0.0
.The value being returned from the std::accumulate function is an integer, not a double because of this:
The template parameter inference done by the C++ compiler makes the return type of the
accumulate
function the same as theinit
parameter, which in your case is an integer. Therefore the return value is being rounded to the nearest whole number. The return value is then being implicitly cast back into a double when it's assigned intosum
.To fix this, you can simply pass the zero as a double (i.e.
0.0
) instead.The last argument of the
std::accumulate
call determines the type of the internal sum as well as the return type. Since0
is anint
everything gets rounded down during addition, and the result is an integer as well.