I need help on Last c++ exercise!!!

I need help doing this problem. here is the instructions,
We would like to calculate the (biased) variance of an array inputted from array:dat by passing a function as a parameter


variance = [(X[0]􀀀mean)2 +(X[1]􀀀mean)2 +  +(X[6]􀀀mean)2]=7

In the following program variance.cpp you need to define function
{float var (float, int);} and modify function { float sum (float (*) (float, int), int*, int s);}
to complete the program of calculating the variance. The code segments to be
defined are underlined).



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  //variance.cpp
#include<iostream>
using namespace std;
float sum (float (*) (float, int), int*, int s);
float var (float, int);
int main(){
int a[10] = {8,5,12,6,13,11,9,7,10,14}; // input from array.dat instead
int s = (sizeof a)/4;
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, int), int *n, int s) {
float sum=0; int *p=n;
...// calculate mean
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
...}



2 Bonus mark if you could utilize the same function sum() to also calculate
mean, instead of calculating mean using a separate loop. Hints: Use global variable
or call sum(NULL,) inside sum().
The output would look like the following:
Mean is 9.5
Variance is 8.25
Last edited on
Topic archived. No new replies allowed.