### Standard deviation problem

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)
 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` ``````else { for(n=0; n>arrayNum[n]; } } int sum = 0; for (int j = 0; j < choosenNum; j++) //Sum of values { sum += arrayNum[j]; } cout <<"Sum of the numbers: " <
The CalcStanDev is wrong.

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:
 ``123456789101112131415161718`` ``````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.
Last edited on
I don't believe this works. You need to return the sqrt of the variance, you are returning the sqrt of the numerator.

return sqrt(sumSquared/(double(nValues)-1));
Topic archived. No new replies allowed.