In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
My version is spelt differently so adjust the code accordingly if copying and pasting.
Chapter 4 Exercise // 4.3
Read a sequence of double values into a vector. Think of each value as the distance between two citis along a given route. Compute and print the total distance (the sum of all distances). Find and print the smallest and greatest distance between two neighboring cities. Find and print the mean distance between two neighboring cities.
#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;
int main()
{
vector<double> distances;
double miles;
cout << "Please enter distances between 2 cities, press enter, ctrl+z, then enter again to finish: \n";
while (cin >> miles)
distances.push_back(miles);
if (distances.size() == 0)
{
cout << "No values entered, Please try again. \n";
}
else
{
//sum
double sum = 0;
for (double i : distances)
sum += i;
cout << "The sum of all distances is: " << sum << endl;
//largest & smallest
sort(distances);
cout << "The smallest distance is: " << distances[0] << endl;
cout << "The largest distance is: " << distances[distances.size() - 1] << endl;
//mean
cout << "The mean of all distances is: " << sum / distances.size() << endl;
}
keep_window_open();
return 0;
}
No comments:
Post a Comment