### 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.

 ``123456789101112131415161718192021222324252627282930313233343536373839`` ``````#include 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:
 ``1234567891011121314151617181920212223242526272829`` ``````#include 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.