0

I declared the average to be double at the beginning of int main(). This code compiles and runs fine, except that when it calculates the average it returns it as an int. The goal of this assignment was to create and fill a vector, then calculate the average and find the median. I am stuck on this part. Any ideas??

Thanks and I appreciate any help.

#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;

int main()
{
    int n;
    double average=0;

    cout<<"Vector Length?: "<<endl;
    cin>>n;
    vector<int> data;
    srand(time(NULL));

    for (int i=0; i<n; i++)
    {
        data.push_back(rand()%10+1);
    }
    for (int i=0; i<data.size(); i++)
    {
        cout<<"Vector: "<<i<<" "<< data[i]<<endl;
    }

    average = accumulate(data.begin(), data.end(), 0)/data.size();

    cout<<"Average: "<<average<<endl;

    system ("pause");

    return 0;





}
DarthVoid
  • 604
  • 3
  • 9
  • 21

1 Answers1

5

The type of the initial value parameter to std::accumulate is being deduced as int. So the result of the accumulation is also an int and you then perform integer division.

Change that line to

average = accumulate(data.begin(), data.end(), 0.0)/data.size();
//                                             ^^^

Now the type returned by accumulate will be double.

Praetorian
  • 106,671
  • 19
  • 240
  • 328