Hi,
I want to sum up all values within a vector of doubles, let say [4.5 8 5 90 24 32 58 1.8 17 25]. The sum is 265.3 which isnt to difficult. But when using the accumulate function I get 264!?

#include <iostream>
#include <math.h>
#include <vector>
#include <numeric>

using namespace std;

int main()
{
	// create a vector
	vector<double> a;
	a.push_back(4.5); a.push_back(8.0); a.push_back(5.0); a.push_back(90.0);
	a.push_back(24.0); a.push_back(32.0); a.push_back(58.0); a.push_back(1.8);
	a.push_back(17.0); a.push_back(25.0);

	for (int i=0;i<a.size();i++)
	{
		// print the vector elements
		cout << a[i] << " ";
	}

	// Sum up values in vector
	double sum = accumulate(a.begin(),a.end(),0);
	// Calculate mean
	double mean = sum/a.size();

	cout << "\nSum:  " << sum << endl;
	cout << "Size: " << a.size() << endl;
	cout << "Mean: " << mean << endl;

	//NOTE: sum = 265.3 !?
}

Output:
4.5 8 5 90 24 32 58 1.8 17 25
Sum: 264 // <-- THIS IS WRONG!?
Size: 10
Mean: 26.4

Thanks for any help.
Andy

Try this

double sum = accumulate(a.begin(),a.end(),0.0);

Thanks. Works now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.