Print out Median

I've done the code below and read the chapter two times and tried searching for similar problems that might help me but I can't seem to know how to make the code work so that it always prints out a median. Any help will be much appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<double> temps;
    double temp;
    while (cin>>temp)
        temps.push_back(temp);


   double sum = 0;
   for (int i = 0; i<temps.size();++i)sum += temps[i];
   cout<<"average temperature: "<<sum/temps.size()<<endl;

   sort(temps.begin(),temps.end());
   cout<<"Median temperature:" <<temps[temps.size()/2]<<endl;

}
Your while loop here
1
2
while (cin>>temp)
        temps.push_back(temp);

will never exit because it will never be false. Try adding something like this
1
2
3
while (cin>>temp && temp != 0){
        temps.push_back(temp);
}

You could then use a do while loop if you don't want the zero to be put into the vector.
1
2
3
4
do {
        temps.push_back(temp);
    }
    while (cin>>temp && temp != 0);

This way the loop will exit when the user enters 0 and the rest of your program can continue executing.
Last edited on
Topic archived. No new replies allowed.