Design a program which repeatedly asks a user for a number (or q to quit) in a w
ID: 3815276 • Letter: D
Question
Design a program which repeatedly asks a user for a number (or q to quit) in a while loop, and then reports the current maximum, minimum, average and standard deviation for all numbers given throughout. You will therefore need to store these numbers somewhere; in this case, a single vector. You will need to use the double variable type for numbers, rather than integer. This will allow for numbers with decimal values. To calculate standard deviation, you will need to include cmath. Then, use the following formula:
Explanation / Answer
code: (Please find comments in code for explanation)
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
cout << "Enter numbers (q to quit): " << endl; // prompting user for inputs
double input, num, min, max, average, sum = 0, std_deviation = 0; // initializing variables
vector<double> numbers; // vector to store inputs
while (cin >> input && input != 'q') // reading input and storing in vector until user enters q
{
numbers.push_back(input);
}
// initializing min and max to first input
min = numbers[0];
max = numbers[0];
num = numbers.size();
// loop to find out sum of all numbers, minimum number entered, maximum number entered
for(int i = 0; i < num; i++)
{
sum += numbers[i];
if(min > numbers[i])
min = numbers[i];
if(max < numbers[i])
max = numbers[i];
}
// calculating average of all numbers entered. (sum of numbers / total numbers entered)
average = sum / num;
cout << min << " " << max << " " << sum << " " << average << endl;
// loop to find sum of square of (each number - average)
for(int i = 0; i < num; i++)
{
std_deviation += pow((numbers[i] - average), 2);
}
// finding final standard deviation
std_deviation = sqrt(std_deviation / num);
// printing values to STDOUT
cout << "The minimum number entered is: " << min << endl;
cout << "The maximum number entered is: " << max << endl;
cout << "The average of entered numbers is: " << average << endl;
cout << "The standard deviation for entered numbers is: " << std_deviation << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.