Vector Class : Write a C++ program that reads an unspecified number of temperatu
ID: 3758673 • Letter: V
Question
Vector Class: Write a C++ program that reads an unspecified number of temperatures in Fahrenheit from the keyboard (prompt the user to enter them one at a time). The values should be added to a vector using the vector class with the push_back function. Instruct the user to enter an invalid temperature (<-459.4) to indicate that they are done entering values. Use functions and algorithms in the <algorithm> and <numeric> libraries to find the max, min, sum, and count (number of values) and display the results. Also sort the temperatures in increasing order and display the values. Include units with all outputs. Print the program along with an example that includes at least 10 valid temperatures.
Explanation / Answer
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
using namespace std;
int main(){
vector<double> vc;
vector<double>::iterator result, temp;
cout<<"Enter temperatures (enter below -459.4 to exit): ";
while (true) {
double c;
cin>>c;
if(c < -459.4) {
break;
}
vc.push_back(c);
}
result = max_element(vc.begin(), vc.end());
cout <<"max = "<<*result<<" ";
result = min_element(vc.begin(), vc.end());
cout <<"min = "<<*result<<" ";
cout<<"Sum="<<accumulate(vc.begin(), vc.end(), 0)<<" ";
for (temp=vc.begin(); temp != vc.end(); ++temp) {
int r = std::count (vc.begin(), vc.end(), *temp);
std::cout << *temp<<" appears " << r << " times. ";
}
cout<<" Sorted data: ";
sort(vc.begin(), vc.end());
for (temp=vc.begin(); temp != vc.end(); ++temp) {
cout<<*temp<<", ";
}
cout<<" ";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.