Hi,
I still can't figure out where this program goes wrong. It keeps producing undefined behavior... Please help. Thank you.
I still can't figure out where this program goes wrong. It keeps producing undefined behavior... Please help. Thank you.
Code:
// Exercise 8.12 - Version 1
#include "std_lib_facilities.h"
/*
[COLOR="Red"]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?[/COLOR]
*/
struct Stats_results {
double mean;
double median;
double max;
double min;
};
Stats_results compute_stats(vector<double> data)
{
Stats_results results;
// mean
double sum = 0;
for (unsigned int i = 0; i < data.size(); ++i)
sum += data[i];
results.mean = sum / data.size();
// median
sort(data.begin(), data.end());
if (data.size()%2==0)
results.median = (data[data.size()/2] + data[data.size()/2 - 1])/2;
else
results.median = data[data.size()/2];
// max
results.max = data[data.size() - 1];
// min
results.min = data[0];
return results;
}
int main()
try {
Stats_results myresults;
cout << "Enter some numbers for a vector: \n";
vector<double> v;
double x;
while (cin >> x)
v.push_back(x);
if (v.size() == 0) error("Empty vector!\n"); // make sure the user input data
compute_stats(v);
cout << "Mean: " << myresults.mean << '\n';
cout << "Median: " << myresults.median << '\n';
cout << "Max: " << myresults.max << '\n';
cout << "Min: " << myresults.min << '\n';
}
catch (runtime_error e) {
cout << e.what() << '\n';
}