//
// source code: mean.cc 
// purpose:     calculates mean and r.m.s of input values
// author:      T. Hebbeker   
// version:     1.0, 2006-10-18
//
// (inspired by program auswertung.cc, DV 2005, Erdmann,Kappler et al)
//

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
  cout << endl 
       << " program   === mean ===   version 1.0 " 
       << endl << endl;

  // here we declare the variables needed
  // it is a good practice to assign initial values to all of them.

  double x             =  -1.;
  int    n_x           =   0;
  double sum_x         =   0.; 
  double sum_x2        =   0.;
  double mean_x        =  -1.;
  double sigma_x         =  -1.;

  // get input data

  // console input: Ctrl-d  = EOF

  cout << " Enter value: ";
  cin  >> x;

  while(!cin.eof())
  {
    cout << endl << "value = " << x << endl;
    n_x++;
    sum_x  += x;
    sum_x2 += pow(x, 2);

    cout << " Enter value: ";
    cin  >> x;
  }

  // check if n_x positive

  if(n_x <= 0)
  {
    cout << " ERROR: no input data ! " << endl;
    return 1;  
  }

  // calculate mean 

  mean_x = sum_x / n_x;

  // and sigma = standard deviation  
  //   - but only if there are >=2 numbers:

  if(n_x >=2)
  {
    sigma_x = sqrt( ( sum_x2 - pow(sum_x,2)/n_x ) / (n_x-1) ); 
  }

  // print results to console:

  cout << endl  << endl 
       << " number of input values  = " << n_x << endl
       << " mean                    = " << mean_x << endl
       << " standard deviation      = " << sigma_x
       << endl;

  return 0;
}


