using vector accumulate function

I am having problems using the accumulate to find the sum of all elements in a vector. Here is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <istream>
#include <string>
#include <vector>
#include <numeric>
using namespace std;

int main()
{
	vector<float> energy;

	for(int i = 0; i < 25; i++)
		energy.push_back(5.364*i); 

	float sum = accumulate(energy.begin(),energy.end(),0);
	cout << "Sum: " << sum << endl;
};


I would like this program to calculate the sum of all elements in the energy vector. When I try to compile, I get a list of about 50 errors relating to the numeric header file. Can somebody tell me whats wrong with my code please.
What errors?

It compiles fine for me (using Visual Studio 2008). Even the warnings vanish if I swap 5.364 for 5.364f and 0 for 0.0f (in the accumulate).

Andy

P.S. I get 1609.2
std::accumulate synthesizes its return type from the third parameter. The literal value "0" is an int, however you are summing floats. You need to tell the compiler that "0" means "float". To do that, use "0.0f" instead.

 
float sum = std::accumulate( energy.begin(), energy.end(), 0.0f );


Out of interest, what errors are you getting?

Andy
Topic archived. No new replies allowed.