find average of input to vector c++

alfiej12 picture alfiej12 · Feb 18, 2015 · Viewed 70.4k times · Source

I am trying to write a program where the user inputs as many numbers as they want and then the program returns the average of the numbers. So far the program only outputs the last number entered.

#include <vector>
#include <iostream>
#include <numeric>


using namespace std;

int main()
{  
    vector<float> v;
    int input;

    cout << " Please enter numbers you want to find the mean of:" <<endl;
    while (cin >> input);
    v.push_back(input);

float average = accumulate( v.begin(), v.end(), 0.0/ v.size());
cout << "The average is" << average << endl;

return 0;  

}

Answer

P0W picture P0W · Feb 18, 2015

First get rid of semi-colon after while

while (cin >> input);
                    ~~

Second you math is wrong

third argument to std::accumulate is initial value of sum

Instead do:

auto n = v.size(); 
float average = 0.0f;
if ( n != 0) {
     average = accumulate( v.begin(), v.end(), 0.0) / n; 
}

Also, the element of container data type should match the container type i.e. float

use float input ;