0

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

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by andy.apple
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.