Hello everyone,
I am writing a main code which uses a subroutine which has some mathematical function in its argument list. Let's say the subroutine (call it
double Integrate(...,..,..)) does integration and that a mathematical function (e.g.f(x) = sin(x)) is in the argument list of subroutine declaration and definition. How to do that in C++? The function's value (f(x)) will be evaluated within subroutine so it seems I cannot define
f(x) as a variable with fixed value in the argument list. How to ascribe form of f(x) in this case? Should I do it in the main() by writing s'thing like
You don't understand what a function is.
A function is (nearly. There's a merely semantical difference that's not relevant to this discussion) synonymous with subroutine. A subroutine is a piece of code that performs some operation based on data passed to it, and that can be executed from any other subroutine that knows it exists.
When a subroutine returns a value, it is similar to the concept of "function" found in mathematics: both give a result based on some value. However, where mathematical notation reads
f(x)=sin(x)
C/++ source reads
1 2 3
double f(double x){
return sin(x);
}
(It could be said that the mathematical notation is a shorthand of this syntax.)
What you want to do can be done, but you will be limited by the number of parameters and you'll have to recompile if you need to change the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
double integrate( //integrate() returns a double and takes:
double(*f)(double,double,double), //a pointer to a function that takes three
//doubles and returns a double;
double x0, //a double;
double x1){ //and a double.
//Integrate.
}
double f(double x,double y,double z){
//return sin(x);
//Function body here.
}
int main(){
double s=integrate(&f,-10,10);
return 0;
}