I have written the program below to calculate Standard deviation and mean of a given file of data. If I run it gives the wrong answers. Can someone help me go along?

#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);
             ~Statistics();
             void Accumulate(double data);
             double mean()const;
             double sigma()const;
             void Print() const;

};


int main(){

    double data;

    Statistics a(data, 200);
    a.Print();

    system("PAUSE");
    return EXIT_SUCCESS;
}

Statistics::Statistics(double _x, int n):x(_x),n(n){}

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

void Statistics::Accumulate(double data){//This should add a data item to the accumulated  statistics
     ifstream in("file.txt");
     for(int i=0; i < n ; i++){
     in >> data;
     sum+=data;
     sum2+=data*data;   
     }
     in.close();
     }
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 ;
}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Use code brackets, makes it easier to read you code segments. Just put (code) before and (code) after your source code without the space between the 'e' and the ].

#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);
~Statistics();
void Accumulate(double data);
double mean()const;
double sigma()const;
void Print() const;

};


int main(){

double data;

Statistics a(data, 200);
a.Print();

system("PAUSE");
return EXIT_SUCCESS;
}

Statistics:tatistics(double _x, int n):x(_x),n(n){}

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

void Statistics::Accumulate(double data){//This should add a data item to the accumulated statistics
ifstream in("file.txt");
for(int i=0; i < n ; i++){
in >> data;
sum+=data;
sum2+=data*data;
}
in.close();
}
double Statistics::mean()const{
return sum/n;
}

double Statistics::sigma()const{
return sqrt( (sum2 - (sum*mean()))/(n-1));
}

void Statistics:rint()const{

cout.precision(8);
cout << " N = " << n <<endl;
cout << " Mean = " << mean() <<endl;
cout << " Sigma = " << sigma()<<endl ;
} 

makes it easier to read that's all ;)

Edited 3 Years Ago by mike_2000_17: Fixed formatting

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