[英]C++ issue with function pointer as parameter
I am trying to apply newtons method in C++ and right now just testing out if my pointers work and are correct. 我正在尝试在C ++中应用newtons方法,现在只是测试我的指针是否有效且正确。 Now the issue is it cannot call the function to test this, it says there is an issue with converting.
现在的问题是它无法调用该函数进行测试,它表示转换存在问题。
My code: 我的代码:
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
double newton(double (*f) (double), double (*fPrime)(double), double intialValue, int iterations);
double f(double x);
double fPrime(double x);
int main() {
int limitIterations = 0;
double intialValue = 0;
cout << "Please enter a starting value for F(X): " ;
cin >> intialValue;
cout << endl << "Please enter the limit of iterations performed: " ;
cin >> limitIterations;
cout << newton(intialValue, limitIterations);
return 0;
}
double f(double x) {
double y;
y =(x*x*x)+(x*x)+(x);
return (y);
}
double fPrime(double x){
double y;
y = 3*(x*x) + 2 * x + 1;
return (y);
}
double newton(double (*f) (double), double (*fPrime)(double), double intialValue, int iterations){
double approxValue = 0;
approxValue = f(intialValue);
return (approxValue);
}
And the error: 错误:
|26|error: cannot convert 'double' to 'double (*)(double)' for argument '1' to 'double newton(double (*)(double), double (*)(double), double, int)'|
You don't need to pass function pointers. 您不需要传递函数指针。 The functions that you defined above can be used directly.
您上面定义的功能可以直接使用。 Just define your
newton
function like this: 像这样定义您的
newton
函数:
double newton(double intialValue, int iterations) {
double approxValue = 0;
approxValue = f(intialValue);
return (approxValue);
}
If you do want to declare newton
to take function pointers, then you will need to pass them in at the call-site to newton
: 如果确实要声明
newton
接受函数指针,则需要在调用站点将它们传递给newton
:
cout << newton(f, fPrime, initialValue, iterations);
The error from the compiler is simply saying that you passed a double
in a slot where it was expecting a function pointer and that it has no clue how to convert a double
into a function pointer double (*)(double)
. 编译器的错误只是说,您在需要函数指针的插槽中传递了
double
,并且不知道如何将double
转换为function double (*)(double)
线索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.