Hello, I'm a C++ beginner and I'm trying to my program (I copied the code from the book : programming principles and practice using C++). This is the code :
// calculate mean and median temperatures
int main()
{
vector<double> temps;
for (double temperatures; cin >> temperatures;)
temps.push_back(temperatures);
// calculate mean temperature
double sum = 0;
for (double x : temps) sum += x;
cout << "The average temperature is : " << sum / temps.size() << "\n";
// calculate median temperature
sort(temps);
cout << "The median temperature is : " << temps[temps.size() / 2 ] << "\n";
return 0;
}
My problem is with the median, the book specify that that's not an appropriate way to calculate the median but for this program it will be ok. If I test the program with the value 2.2 and 3.5 for example I get the value of the mean (ok) and the value of the median, the problem is that sometimes the value of the median is wrong.
If I enter 2 values in input for example, the value of the median should be the element of the vector wich has the index equal to the value of size() / 2. If I enter 6.6 and 1.4 and I terminate the input with end-of file the size should be 2, and the median should be 2 / 2 == 1; So why i get the elemet of the vector with value 0 ? Am I misunderstanding something ?