Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::accumulate is declared as such:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...