我正在尝试在 C++ 中应用 newtons 方法,现在只是测试我的指针是否有效且正确。现在的问题是它无法调用函数来测试它,它说转换存在问题。
我的代码:
#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);
}
错误:
|26|error: cannot convert 'double' to 'double (*)(double)' for argument '1' to 'double newton(double (*)(double), double (*)(double), double, int)'|
最佳答案
如果你确实想声明 newton
来获取函数指针,那么你需要在调用站点将它们传递给 newton
:
cout << newton(f, fPrime, initialValue, iterations);
编译器的错误只是说你在它期望函数指针的槽中传递了一个 double
并且它不知道如何转换一个 double
进入函数指针 double (*)(double)
。
关于函数指针作为参数的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775300/