#include <iostream>
#include <cmath>
using namespace std;
int n;
void main(){
cout<<"input the number of students: ";
cin>>n;
double *scores= new double[n];
cout<<"enter the scores of the students: ";
for( int i=0; i<n; i++){
cin>>scores[i];
}
double sigma,sigma2, mean, strDev;
int ii;
for (sigma=ii=0;ii<n;ii++){
sigma+=*scores;
*scores++;
mean= sigma / n;

}
int iii;
for (sigma2=iii=0;iii<n;iii++){
sigma2+=pow(*scores-mean,2);
*scores++;

}
cout<<"The mean is: "<<mean<<endl;
strDev= pow(sigma2/n,1/2);
//cout<<"The standard deviation is: "<<strDev<<endl;
cout<<sigma2<<endl;
cout<<sigma2/n<<endl;
cout<<*scores<<endl;
}

Hello everyone, I have some quick questions about my code. First of all, I created this 1-dimensional dynamic array where the user can input the number of people in the class and their grades. The problem I'm having right now is that the standard deviation is not working correctly. When I put that there are 5 people (n=5) and that their scores were 1,2,3,4,5, the mean comes out right, but sigma2 which i need for finding out the standard deviation comes to to 45 when it should be 10. Can someone please tell me what is wrong with it?

2
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by sonygamer

Can I please get some help? I've been working on this for hours and I still cannot figure out what is wrong.

In particular is the "cleverness".

Ok first, it is int main() . That has been said a million times on this forum.

Second for (sigma=ii=0;ii<n;ii++) thsi is C++ so (a) reuse index i and declare it in your loop like you have done for the first loop in your code. Second the "clever" sigma=ii=0 is a mess since (i) sigma is a double and ii is an integer and you would have been lots better to write double sigma(0.0),sigma2(0.0) ... etc. on the line above.

Then you make a mistake -- your see scores points the first point in the memory you allocated and you proceed to change that by using it as a point -- so by the end of the first loop (to get mean) you have scores=original_scores + 5 * sizeof(int).

The you don't reset it --- oh --- that means that the next loop is junk, since score loops over the NEXT 5 values that can be absolutely anything.

Finally you allocate memory so please remember

For every new there must be a delete.

You are well able to fix your code by (a) using array indexs e.g. scores or (b) by using a new pointer that is not allocated e.g

double* sPtr=scores;
for(int i=0;i<n;i++)
sum+=*sPtr++;

Finally: Do you know that the line strDev=pow(sigma2/n,1/2); is the same as either strDev=pow(sigma2/n,0); strDev=1.0; Think about integers arithmatic 0.5 would have been better.

Edited by StuXYZ: n/a

Thank you so much StuXYZ for the advice. Everything works well now.
I was even able to add a second dynamic array that would handle the grade Chars and print them out based on the scores inputed.