mean using a vector

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

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

#include "std_lib_facilities.h"

int main() {
	vector<double> distances;
	double distance;

	cout << "Enter a double\n";

	//pushing new temperature values into temps vector
	while (cin >> distance)
	{
		distances.push_back(distance);
		cout << "Enter another double or press n to continue and calculate the sum of distances.\n";
	}

	//calculate sum and display
	double sum = 0.0;
	for (double x : distances)
	{
		sum += x;
	}
	cout << "sum of distances is: " << sum << '\n';

	//calculate smallest and largest
	sort(distances);
	cout << "the smallest distance is: " << distances[0] << '\n';
	cout << "and the largest distance is: " << distances[distances.size() - 1] << '\n';

	//calculate mean distance
	cout << "the mean distance is: " << sum / distances.size() << '\n';

	keep_window_open("-");
}
Output:
Enter a double
4.5
Enter another double or press n to continue and calculate the sum of distances.
6.7
Enter another double or press n to continue and calculate the sum of distances.
8.9
Enter another double or press n to continue and calculate the sum of distances.
n
sum of distances is: 20.1
the smallest distance is: 4.5
and the largest distance is: 8.9
the mean distance is: 6.7
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.