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

#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.

Recommended Answers

All 2 Replies

One thing to note is that accumulate's third parameter, 0 in this case, makes your result an integer because the function takes that type as its value. Therefore, the fractional part of your code would be disregarded.

Change the 0 to 0.0.

Great. It works now! thanks a lot

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.