C Write a function that finds the smallest the largest elem
C++
Write a function that finds the smallest & the largest element of a
vector
argument and also compute the mean and the median. Do not use global
variables.
Either return a struct containing results or pass them back through
reference
arguments. Which of the 2 ways of returning several result values do
you prefer and why?
Solution
The program which is related to the asked question is and please let me know if any error occurs:
struct stats {
vector<double> v;
double mean;
double median;
double max;
double min;
};
void fmean(stats& results)
{
results.mean = sum/results.v.size();
}
void fmedian(stats& results)
{
sort(results.v.begin(), results.v.end());
if (results.v.size()%2 == 0)
results.median = (results.v[results.v.size()/2] + results.v[results.v.size()/2-1])/2;
else
results.median = results.v[results.v.size()/2];
}
void fmin_max(stats& results)
{
results.max = results.min = results.v[0];
for (unsigned int i = 0; i < results.v.size(); ++i) {
if (results.v[i] > results.max)
results.max = results.v[i];
if (results.v[i] < results.min)
results.min = results.v[i];
}
}
int main()
try {
stats myresults;
cout << \"Enter some elements: \ \";
double x;
while (cin >> x)
myresults.v.push_back(x);
fmedian(myresults);
fmean(myresults);
fmin_max(myresults);
cout << \"Mean: \" << myresults.mean << \'\ \';
cout << \"Median: \" << myresults.median << \'\ \';
cout << \"Max: \" << myresults.max << \'\ \';
cout << \"Min: \" << myresults.min << \'\ \';
}
catch (runtime_error e) {
cout << e.what();
}

