Hi,
I'm doing the first exercise on struct. I can't figure out why it doesn't return a correct result for median. It always rounds it up... Say if I input 1 2 3 4, it returns the median == 3, not 2.5, even though it uses type double. Could you please help? Also, could you please help suggest a bit of improvement on the program? I'm learning about struct/class and this exercises asks me to practice using struct...
Code:
// Exercise 8.12
#include "std_lib_facilities.h"
/*
Write a function that finds the smallest & the largest element of 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 one do you prefer, and why?
*/
struct stats {
vector<double> v;
double smallest, largest, median;
double fmean(vector<double>& v);
double fmedian(vector<double>& v);
double fsmallest(vector<double>& v);
double flargest(vector<double>& v);
};
int main()
try {
stats mystats;
vector<double> v;
double x;
cout << "Enter some elements for a vector: \n";
while (cin >> x)
v.push_back(x);
cout << "Here are some summary statistics: \n";
cout << "Smallest: " << mystats.fsmallest(v) << '\n';
cout << "Largest: " << mystats.flargest(v) << '\n';
cout << "Mean: " << mystats.fmean(v) << '\n';
cout << "Median: " << mystats.fmedian(v) << '\n';
}
catch (runtime_error e) {
cout << e.what();
}
double stats::fsmallest(vector<double>& v)
{
smallest = v[0];
for (unsigned int i = 0; i < v.size(); ++i) {
if (v[i] < smallest)
smallest = v[i];
}
return smallest;
}
double stats::flargest(vector<double>& v)
{
largest = v[0];
for (unsigned int i = 0; i < v.size(); ++i) {
if (v[i] > largest)
largest = v[i];
}
return largest;
}
double stats::fmean(vector<double>& v)
{
double sum = 0;
for (unsigned int i = 0; i < v.size(); ++i) {
sum += v[i];
}
return sum / v.size();
}
double stats:: fmedian(vector<double>& v)
{
sort(v.begin(), v.end());
median = 0;
for (unsigned int i = 0; i < v.size(); ++i) {
if (v.size()%2==0)
median = (v[v.size()/2] + v[v.size()/2-1])/2;
median = v[v.size()/2];
}
return median;
}