I have to write a program to calculate sum, mean, variance, and standard deviation and I was able to do the sum and mean but I don't understand the variance and standard deviation.
If the size of the set is 7 and the set is represented by X[0], X[1], X[2], X[3], X[4], X[5], X[6], then the (biased) variance may be computed as:
variance = [(X[0]-mean)2 + (X[1]-mean)2 + ... + (X[6]-mean)2]/7 and the standard deviation is the square root of the variance (use sqrt() in <math.h> to calculate square root of a value)
Run your program two times, using two different sets of data:
· Run I: 7 numbers --- 12, 22, 34, 43, 45, 54, 99
Output:
sum: 309
average: 44.1429
variance: 676.408 <--
standard deviation: 26.0078 <--
*last two don't compute correctly when running the program
· Run II: 8 numbers -- 1.0, 1.5, 2.5, -9.3, 0, -1.0, 3.0, 6.4
Can anyone help? Here is my code so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
// This program calculates the sum, average, variance, and standard deviation of any numbers.
// Using the for structure
using namespace std;
#include <iostream>
#include <math.h>
int main()
{
int n, count;
double x, sum, avg, var, sd;
sum = 0;
cout << "How many numbers? ";
cin >> n;
int array[n];
for(count=0; count<n; count++){
cout << "Enter Number: "; //Changed prompt so it was more user friendly.
cin >> array[n];
sum = sum + array[n];
} //end for
var = 0;
for (count=0; count<n; count++){
var += pow(array[n]-avg,2);
}
var /= n;
avg = sum / n;
sd= sqrt(var);
cout << "The sum is " << sum << endl;
cout << "The average is " << avg << endl;
cout << "The variance is " << var << endl;
cout << "The standard deviation is " << sd << endl;
return 0; //successful termination
}//end main
|