I have written a program to compute mean and median. Please review my code and give suggestions.
I have a confusion about this temps[temps.size()/2]
when temps.size() is an odd number. How does the "vector::operator[]" handle floating point numbers? From the behavior in my code, I guessed it rounds to the nearest integer.
Note: I am self learning programming by reading "Programming: Principles, and Practice" by Bjarne Stroustrup. Currently, I am on chapter 4.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<double> temps; // temperatures
for (double temp; std::cin>>temp; ) // read into temp
temps.push_back(temp); // put temp into vector
// Compute Mean temperature:
double sum = 0;
for (int x : temps) sum += x;
std::cout << "Average temperature: " << sum/temps.size() << '\n';
// sort temperatures
std::sort(temps.begin(),temps.end());
// Compute Median temperature
if(temps.size()%2==1) //Number of elements are odd
{
std::cout << "Median temperature: " << temps[temps.size()/2] << '\n';
}
else // Number of elements are even
{
int index = temps.size()/2;
std::cout<< "Median temperature: " << (temps[index-1] + temps[index])/2;
}
}