In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
My version is spelt differently so adjust the code accordingly if copying and pasting.
Chapter 4 Exercise // 4.2
If we define the median of a sequence as a "number so that exactly as many elements come before it in the sequence as come after it," fix the program in 4.6.3 so that it always prints out a median. Hint: A median need not be an element of the sequence.
#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;
int main()
{
vector<double> temps;
cout << "Please enter integers to find mean & median, press enter, ctrl+z, then enter again to finish: \n";
for (double temp; cin >> temp;)
temps.push_back(temp);
//compute mean temp
double sum = 0;
for (double x : temps) sum += x;
cout << "Average temperature: " << sum / temps.size() << '\n';
//compute median temp
sort(temps);
if (temps.size() % 2 == 0)
cout << "Median temperature: " << (temps[temps.size() / 2 - 1] + temps[temps.size() / 2]) / 2 << endl;
else
cout << "Median Temperature: " << temps[temps.size() / 2] << endl;
keep_window_open();
return 0;
}
Ok this one took me a while, not because I don't know how to calculate the median but I just completely forgot that values inputted into a vector are not labelled 1,2,3,4 etc...but 0,1,2,3,4 etc....
The median on an even amount of numbers is calculated as so:
Lets say we put the numbers 1, 2, 3,4 in. In a vector these are labelled as 1[0], 2[1], 3[2], 4[3]. Therefore when we divide the size by 2 it will return 2 which is the number 3 (it's confusing right?) So temps[temps.size() / 2 - 1] will now return 2 and then we add it to temps[temps.size() /2] to give us 5. We then divide all that by 2 to get 2.5 which is the median.
I made the mistake of having +1 in my calculations and got very annoyed as didn't work, especially since in normal maths terms it should've worked. I've seen the above code a lot whilst I was searching for answers and not one person replied with "vectors start at 0, just -1 instead of +1". Just the standard "Use this instead"....
Thanks for this! I'm just wondering, why does this only work if you press ctrl+z and enter?
ReplyDeleteAh, that's just my compiler, Visual Studio on my pc seems to very particular on how it likes to exit loops and I'm just starting to focus on loops a bit more now so hopefully I won't have to keep doing this in a couple more months.
DeleteBut anyways, I'm glad it helped, I spent a long time on chapter 4.