Read a sequence of doubles into a vector. Think of each value as the distance between two cities 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
cout<< "please enter a whitespace-separated sequence of doubles (representing distances) : ";
vector<double>distances;
for (double distance;cin>>distance;)
distances.push_back(distance);
double sum=0;
for (double x:distances) sum+=x;
min/max of vector?
max_element (distances.begin(), distances.end()); ?
If some of you would be more technically-oriented and know how to find min/max of vector I would appreciate, thanks.
Plans are to start at university at some point, to get my learning going faster :)
#include<algorithm>
#include<iostream>
#include<vector>
usingnamespace std;
int main()
{
cout<< "please enter a whitespace-separated sequence of doubles (representing distances) : ";
vector<double>distances;
for (double distance;cin>>distance;)
distances.push_back(distance);
double sum=0;
for (double x:distances) sum+=x;
cout << "sum of the distances is " << sum << '\n';
cout << "The smallest distance is " << min_element(distances.begin(), distances.end()) << '\n';
cout << "The largest distance is " << max_element(distances.begin(), distances.end()) << '\n';
cout << "The mean distance is" << sum/distances.size() << '\n';
return 0;
}
#include<algorithm>
#include<iostream>
#include<vector>
usingnamespace std;
int main()
{
cout<< "please enter a whitespace-separated sequence of doubles (representing distances) : ";
vector<double>distances;
for (double distance;cin>>distance;)
distances.push_back(distance);
double sum=0;
for (double x:distances) sum+=x;
cout << "sum of the distances is " << sum << '\n';
cout << "The smallest distance is " << *min_element(distances.begin(), distances.end()) << '\n';
cout << "The largest distance is " << *max_element(distances.begin(), distances.end()) << '\n';
cout << "The mean distance is" <<'\t'<< sum/distances.size() << '\n';
return 0;
}
One thing seems strange though. Range based for loops are not allowed in C++98. Is there a way to change the compiler settings so that it would support all these modern standards. Because it is a pain to write always -std=c++11.
Or maybe I should just write in C++98 mode, why not, people managed to write with that standard back then.