Why is the std::accumulate function showing the wrong sum of a vector<double>?

Viewed 5366

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 doubles?

4 Answers
Related