当前位置: 代码迷 >> 综合 >> C++ 函数指针的应用
  详细解决方案

C++ 函数指针的应用

热度:59   发布时间:2023-10-24 01:55:53.0

函数指针的应用

函数指针的定义:

类型名称  函数名称(函数类型 (*函数名称)(函数参数类型))

如:double newton(double (*f)(double),double (*f_prime)(double))

函数指针的调用:

(*函数名称)(函数参数)

如:(*f)(x)

1. 函数,可以通过定义函数参数的方式,实现输出不同的结果。

可看下题:

1.定义了一个 double newton(double (*f)(double),double (*f_prime)(double)) ,的函数。其参数均为函数指针。

2.再定义了 同上述函数参数 相同的 两个函数。因为类型一致,即便与 newton 函数定义的函数参数名称不一致,也可以顺利运行。

那么这样做的意义是什么:

则是 newton 函数,可以用于执行函数参数名称不同,但是函数类型一致的函数的结果。

#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;#define EPSILON 1e-6double f(double x) {return 2 * pow(x, 3) - 4 * pow(x, 2) + 3 * x - 6;
}double f_prime(double x) {return 6 * pow(x, 2) - 8 * x + 3;
}double h(double x){return pow(x,3) - 4 * pow(x,2) + 3 * x - 6;
}double h_prime(double x){return 3 * pow(x,2) - 8 * x +3;
}double newton(double (*f)(double),double (*f_prime)(double)) {double x = 1.5;while (fabs((*f)(x)) > EPSILON){x = x - (*f)(x) / (*f_prime)(x);}return x;
}int main() {cout<<newton(f,f_prime)<<endl;cout<<newton(h,h_prime)<<endl;return 0;
}

 

  相关解决方案