median using a vector

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 4 Exercise 2
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PP
//	Chapter 4 Exercise 2

#include "std_lib_facilities.h"

int main() {
	vector<double> temps;
	double temp;
	
	cout << "Enter a double\n";

	//pushing new temperature values into temps vector
	while (cin >> temp)
	{
		temps.push_back(temp);
		cout << "type another double or press n to continue and calculate the median temperature.\n";
	}
	
	//displaying vector size
	cout << "size of vector: " << temps.size() << '\n';

	//sorting temps vector
	sort(temps); //sort(temps.begin(), temps.end());
	
	//calculate median
	double median;
	if (temps.size() % 2 == 0)
		median = (temps[temps.size() / 2 - 1] + temps[temps.size() / 2]) / 2;
	else
		median = temps[temps.size() / 2];
	cout << "Median temperature: " << median << endl;

	keep_window_open("-");
}
Output:
Enter a double
2.3
type another double or press n to continue and calculate the median temperature.
2.6
type another double or press n to continue and calculate the median temperature.
n
size of vector: 2
Median temperature: 2.45
Please enter - to exit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.