Reputation: 25
I am having some trouble understanding what a few lines mean in a code. I recently started learning C++ and picked up Bjarne Stroustrup's "Programming: Principles and Practice Using C++." There is a question in chapter 4 that was tripping me up, so I searched for a solution online to reference. Here is the code I ended up using in conjunction with the book:
#include "std_lib_facilities.h"
int main()
{
vector<double> temps;
for (double temp; cin >> temp;)
temps.push_back(temp);
double sum = 0;
for (double x : temps) sum += x;
cout << "Average Temperature: " << sum / temps.size() << "\n";
if (temps.size() %2==0) {
sort(temps);
cout << "Median Temperature: " << (temps[temps.size() / 2 - 1] + temps[temps.size() / 2]) / 2 << "\n"; //line one
} else {
sort(temps);
cout << "Median Temperature: " << temps[temps.size() / 2] << "\n"; //line two
}
keep_window_open();
return 0;
}
I commented on the lines that I don't understand. What exactly is happening with these vectors? I understand that "temps.size()" is used to call upon the elements within a vector and that usually the "-1" means to take the last value. However, when I try and think this through in my head, it just doesn't make sense in conjunction to the outputs. Yes, the output is correct in the code, but could someone please help explain those lines to me? I simply don't want to just copy and paste code and not understand it. I need help understanding at a basic level how the code is being outputted correctly so that I can make my own solution. Thanks!
Upvotes: 1
Views: 136
Reputation: 678
The median of a data set is the value for which half the data is above the median and half the data is below the median. If there is an odd number of data points, it is the value of the middle data point. If there are an even number of data points, it is the arithmetic mean of the two central data points.
The if statement before line 1 checks if there is an even or an odd number of data points. If the comparison is true, there are an even number of data points, and therefore you need to take the average of the temps[temps.size()/2-1]
(which is the maximum value under the median) and temps[temps.size()/2]
(which is the minimum value over the median). If the comparison is false, then there are an odd number of elements, and therefore the median is the middle element temps[temps.size()/2]
.
Upvotes: 1
Reputation: 2134
Well it comes mathematics: Median definition. So, the code just follows the definition.
I understand that "temps.size()" is used to call upon the elements within a vector and that usually the "-1" means to take the last value. However, when I try and think this through in my head, it just doesn't make sense in conjunction to the outputs.
No, here, it takes temps.size()/2 -1
, the middle element of vector, not the last.
Upvotes: 1