C++ Help! I have this following code and it works to find the average. But now I
ID: 3667644 • Letter: C
Question
C++ Help!
I have this following code and it works to find the average. But now I need to find the standard deviation and im not sure where to start. I have it prompt a user to how many values they will enter in, it will then ask for the values and put the values in a vector. Afterwards it calculates the average. Now I just need it to calculate the standard deviation. Nothing fancy, I need it to be relatively simple really. Here is the code I have so far.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
// Create vector
vector<double> values;
// Declare variables
double count;
double value;
double average = 0;
double stdDev;
double var;
// Prompt user and get the number of values
cout << "How many values will you enter? ";
cin >> count;
// Get the values from user and calculate average
for( double i = 0; i<= count; i++)
{
cin >> value;
values.push_back(value);
average+=values[i];
}
cout << average/count << ' ';
return 0;
}
Explanation / Answer
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
/* Create vector */
vector<double> values;
/* Declare variables*/
double count;
double value;
double average = 0;
double stdDev;
double var=0;
/* Prompt user and get the number of values */
cout << "How many values will you enter? ";
cin >> count;
/* Get the values from user and calculate average */
for( double i = 0; i < count; i++)
{
cin >> value;
values.push_back(value);
average+=values[i];
}
average = average/count ;
cout << "average = "<<average << ' ';
//Variance Calculation
for( double i = 0; i < count; i++)
var += ( average - values[i] ) * ( average - values[i] );
var /= count;
cout << "variance = "<<var << ' ';
//STandard Deviation Calculation
stdDev = sqrt(var);
cout << "standard deviation = "<<stdDev << ' ';
return 0;
}
----------------------------
Input :
5
2
3
4
5
6
Ouput:
--------------------
average = 4
variance = 2
standard deviation = 1.41421
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.