variance and mean

I have to output Mean and Variance, I can get output for Mean but not the Variance. Can you please look at my code and help me on how to input code for the Variance.

//variance.cpp

#include<iostream>

#include <fstream>

#include <math.h>

using namespace std;

float sum (float (*) (float, int), int*, int s);

float var (float, int);

ifstream infile ("array.dat");

int main(){

int array = 10;
int s = 0;
int a[array];
while(infile >> a[s]) {s++;}

cout << "Mean = " << sum(NULL, a, s) << endl;

cout << "Variance=" << sum(var, a, s) << endl;

cout << "\n\n\nPress any key to close console window: ";

char c; cin >> c;

return 0;

}

float sum (float (*pf) (float mean, int), int *n, int s) {

float sum=0; int *p=n;

float mean=0;

mean = sum / s;

for (int i=0; i<s; i++) {

if (pf == NULL) sum+= *p;

else sum+= (*pf)(mean, *p);

p++;

}

return sum/(s);

}

float var (float mean, int k)

{

return k*k;

}
Why oh why don't you just have two functions called variance and mean that calculate the variance and mean respectively?

Does infile need to be global?

Does that even compile?
Topic archived. No new replies allowed.