Function Pointers

Any idea where I am going wrong? We have to make a function integrate to work with the other functions given. I had it working before but I would only get all -4 as my answers but only the first one should be -4. can someone please provide me with what should more or less be put in my integrate function?

#include <iostream>
using namespace std;

typedef double (*FUNC)(double, double, double) = (line, square, cube);

double integrate(double FUNC, double a, double b){
for(int i=0; i<a && i<b; i++){
FUNC = a-b;
}
return FUNC;
}

double line(double x){
return x;
}

double square(double x){
return x*x;
}

double cube(double x){
return x*x*x;
}

int main(){

cout << "The integral of f(x)=x between 1 and 5 is: " << integrate(line,1,5) << endl;
cout << "The integral of f(x)=x^2 between 1 and 5 is: " << integrate(square,1,5) << endl;
cout << "The integral of f(x)=x^3 between 1 and 5 is: " << integrate(cube,1,5) << endl;
system("pause");

}
What you intended to do was somthing like the following. You either needed to put your functions before you are using them in your code or at least put some function declarations.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;

double line(double x)
{
	return x;
}
 
double square(double x)
{
	return x*x;
}
 
double cube(double x)
{
	return x*x*x;
}
 
enum FUNCS
{
	LINE,
	SQUARE,
	CUBE
};

double integrate(double x, FUNCS func)
{
	typedef double (*FP)(double);
	static FP funcs[] = {line, square, cube};
	return funcs[func](x);
}
 
int main()
{
	cout << "The integral of f(x)=x between 1 and 5 is: " << integrate(5, LINE) << endl;
	cout << "The integral of f(x)=x^2 between 1 and 5 is: " << integrate(5, SQUARE) << endl;
	cout << "The integral of f(x)=x^3 between 1 and 5 is: " << integrate(5, CUBE) << endl;
	system("pause");
}
Last edited on
well, b-a will give -4 in case of the line. But that's not an integral. See

http://en.wikipedia.org/wiki/Integral


Maybe you think of something like that:
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
27
28
29
#include <iostream>
using namespace std;

typedef double (*FUNC)(double);

double integrate(FUNC f, double a, double b){
return f(b) - f(a);
}

double line(double x){
return x;
}

double square(double x){
return x*x;
}

double cube(double x){
return x*x*x;
}

int main(){

cout << "The integral of f(x)=x between 1 and 5 is: " << integrate(line,1,5) << endl;
cout << "The integral of f(x)=x^2 between 1 and 5 is: " << integrate(square,1,5) << endl;
cout << "The integral of f(x)=x^3 between 1 and 5 is: " << integrate(cube,1,5) << endl;
//system("pause");

}
Topic archived. No new replies allowed.