I have it down to this:
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
|
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int N = 0;// size of the sample
double x = 0.0, sum = 0.0, sumSq = 0.0;
cout << "How many numbers in the sample? ";
cin >> N;
cout << endl << "Enter " << N << " numbers." << endl;
for(int i=1; i<=N; ++i)
{
cin >> x;
sum += x;
sumSq += x*x;
}
cout << "the average of the " << N << " numbers = " << sum/N << endl;
cout << "stdDev = " << sqrt( (sumSq - sum*sum/N)/N ) << endl;
cout << endl;
return 0;
}
|
Unfortunately, our programs give different results.
For this sample of 7 numbers: 2, 8, 15, 6, 25, 4, 20
Your program gives: avg = 11, stdDev = 8.64374
Mine gives: avg = 11.4286, stdDev = 8.06858
You're getting the wrong value for average because both num and OriginalAmountOfNumbers are integers. When you calculate average on line 39:
average = num / OriginalAmountOfNumbers;
this performs integer division and the decimal part gets truncated.
OK. That's where the problem is. I changed your line 39 to:
average = (double)num / OriginalAmountOfNumbers;
and now the results agree.