Hey. I'm trying to write a program that calculates the standard deviation. Visual basic doesn't give me any errors, but I think that the result is wrong.
Can anyone see whats wrong?
My code:(not all of the code, but the problem should lie here)
You call it like this:
CalcStanDev(deviation, meanValue, arrayNum[n], choosenNum);
The first problem is that arrayNum[n] is out of bounds because n currently represents the number of elements in the array.
The second problem is that even if n wasn't out of bounds, you're just passing a data member into CalcStanDev. This isn't the equation.
You want something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
double Avg(double Values[], int nValues)
{
double sum = 0;
for (int i = 0; i < nValues; ++i)
sum += Values[i];
return sum / (double(nValues));
}
double StDev(double Values[], int nValues)
{
double mean = Avg(Values, nValues);
double sumSquared = 0;
for (int i = 0; i < nValues; ++i)
sumSquared += (Values[i] - mean) * (Values[i] - mean);
return sqrt(sumSquared) / (double(nValues) - 1.);
}
In general, you want to do everything you can inside of a function. The main() should only be used for higher level operations. So when we compute an average, we want to do the summing inside of the function, not outside. We also want to make the interface (parameter list) as simple as possible. In both cases of calculating the Average and StDev, all we need is the list of numbers and the number of values.