Wednesday 2 May 2018

Chapter 8 // Exercise 11 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


Chapter 8 // Exercise 11



11. Write a function that finds the smallest and the largest element of a vector argument and also computes the mean and median. Do not use global variables. Either return a struct containing the results or pass them back through reference arguments. Which of the two ways of returning several result values do you prefer and why?

#include "stdafx.h"
#include "std_lib_facilities.h"

struct stats
{
 double smallest;
 double largest;
 double mean;
 double median;
};

//print vectors to the screen
void print(const vector<double>& price)
{
 for (int i = 0; i < price.size(); ++i)
 {
  cout << price[i] << endl;
 }

 cout << "--------------------------------" << endl;
}

//print struct
void print(const stats& s)
{
 cout << "Largest: " << s.largest << endl;
 cout << "Smallest: " << s.smallest << endl;
 cout << "Mean: " << s.mean << endl;
 cout << "Median: " << s.median << endl;
}

stats findVectorStats(const vector<double>& v, vector<double> v_copy, stats& stat)
{ 
 //initialise values
 stat.largest = v[0];
 stat.smallest = v[0];
 stat.mean = v[0];
 stat.median = v[0];
 
 //if vector only has 1 value return that
 if (v.size() == 1)
  return stat;

 for (int i = 0; i < v.size(); ++i)
 {
  //if next value is bigger than last, make that new largest
  if (stat.largest < v[i])
   stat.largest = v[i];
  //if next value is smaller than last, make than new min
  else if (stat.smallest > v[i])
   stat.smallest = v[i];

  //add numbers together for mean calculation
  stat.mean += v[i];
 }

 //find mean
 stat.mean = stat.mean / v.size();

 //find median by sorting to find middle number
 sort(v_copy.begin(), v_copy.end()); //put in ascending order

 //if vector has odd number of items
 if (v_copy.size() % 2 != 0)
 {
  stat.median = v_copy[(v_copy.size() / 2)];
 }
 //if vector has even number of items
 else
 {
  stat.median = (v_copy[v_copy.size() / 2 - 1] + v_copy[v_copy.size() / 2]) / 2;
 }

 //return struct
 return stat;
}

int main()
{
 vector<double> numbers = { 1, -9, 2, 3, 3, 3, 1500 };

 stats findStats;
 
 findVectorStats(numbers, numbers, findStats);

 print(findStats);

 keep_window_open();

 return 0;
}


I really wanted to separate all the different operations into their own functions however Bjarne said to create just one. I also decided to return a struct of all the values to save having four separate variables in main().

No comments:

Post a Comment