Hello ladies and gents,
Had to make the following exercise in Accelerated C++
Write a program to calculate the average of the numbers stored in a vector<double>.
THis was my solution:
#include <iostream>
#include <iomanip>
#include <vector>
using std::cin; using std::istream;
using std::cout; using std::setprecision;
using std::endl; using std::vector;
istream& vec(istream&, vector<double>&);
double median(vector<double>&);
int main()
{
vector<double> numbers;
cout << "Fill the vector with double values. To quit, press Ctrl 'z'." << endl;
vec(cin, numbers);
cout << "The average of these numbers is " << setprecision(2) << median(numbers) << endl;
cin.ignore(1, '\0');
return 0;
}
istream& vec(istream& is, vector<double>& number)
{
double numb;
while (is >> numb)
number.push_back(numb);
cin.clear();
return is;
}
double median(vector<double>& nr)
{
double average = 0.0;
for (int i = 0; i < nr.size();++i)
average += nr[i];
return average/nr.size();
}
Would you change anything in it, and if so, why?
Thanks.