//I need to make a class that calculate the mean and standard deviation. I have to test my program with an external file containing about 300 data. My program doesnt return the correct valuesAny help?

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;
class Statistics{
      double x;
      int n;
      double sum;
      double sum2;
      
      public:
             Statistics(double _x, int _n);
             void Accumulate(double data);//
             ~Statistics();
             double mean()const;
             double sigma()const;
             void Print() const;
             
};
                                            

int main(){

double data; 
double sum=0.0,sum2=0.0; 
    int n=300;
     ifstream in("file.txt");
     for(int i=0; i <= n ; i++){
     in >> data;

     sum+=data;
     sum2+=data*data;	
     }
     in.close();
     
     Statistics a(data, 300);
     a.Print(); 

     system("PAUSE");
     return 0;
}

Statistics::Statistics(double _x, int _n){
x=_x;
n=_n;

}

Statistics::~Statistics(){
cout<<"Statistics destructor called"<<endl;
     }
     

void Statistics::Accumulate(double data){
     sum+=data;
     sum2+=data*data;
     }
     
double Statistics::mean()const{
     return sum/n;
     }

double Statistics::sigma()const{   
     return sqrt( (sum2 - (sum*mean()))/(n-1));
     }
     
void Statistics::Print()const{
     
     cout.precision(8);
	 cout << " N     = " << n <<endl; 
     cout << " Mean  = " << mean()<<endl;
	 cout << " Sigma = " << sigma()<<endl ;
}

I suggest you hard code some values instead of reading them from a file. You should know exactly what the output should be. Then you can tell and show us what you have given for input, what you expect the output to be, and what the output currently is. Is the mean wrong? Is the standard deviation (which you should name the function instead of sigma) wrong?

You still have a couple of design issues (bugs).

In particular look at the value n. It is suppose to be the number of data items added, but actually you set it in the constructor, why not increase it each time that you add some data, and set it to zero in the constructor.

What purpose does x have??

This article has been dead for over six months. Start a new discussion instead.