C++ 函数指针的应用

函数指针的应用

函数指针的定义:

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

如: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-6

double 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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值