[英]C++ issue with function pointer as parameter
我正在嘗試在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
函數:
double newton(double intialValue, int iterations) {
double approxValue = 0;
approxValue = f(intialValue);
return (approxValue);
}
如果確實要聲明newton
接受函數指針,則需要在調用站點將它們傳遞給newton
:
cout << newton(f, fPrime, initialValue, iterations);
編譯器的錯誤只是說,您在需要函數指針的插槽中傳遞了double
,並且不知道如何將double
轉換為function double (*)(double)
線索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.