指向参数减少的函数的指针 [英] Pointer to a function with reduced arguments

查看:14
本文介绍了指向参数减少的函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数指针有问题:

我需要对一个函数进行数值积分,因此希望将带有该函数的指针传递给积分器".问题是,要集成的函数需要的参数不止一个.类似的东西:

I need to numerically integrate a function and want therefore pass a pointer with the function to the "integrator". The problem is, that the function to be integrated takes more then just one argument. Something like:

double f(int i, double x){ // i to switch the function, x to evaluate
  if(i==1) {return sin(x);}
  if(i==2) {return exp(x);}
}

double integrate(double (*function)(double), double x0, double x1){
//integrate the passed *function from x0 to x1
}

int main(){
  int i=1; // i want to chose sin(x)
  cout << integrate(&f, 0, 5);
}

我怎样才能修正一个论点而只传递剩下的?感谢您的帮助!

How can i fix a argument and just pas on the remaining? Thanks for your help!

附注.在我必须搜索什么之后,从面向对象编程的角度来看,什么是关键字?

PS. after what do I have to search, what are keywords, also in perspective to object orientated programming?

推荐答案

应该这样做...

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

typedef double (*f_ptr)(double);

double f_sin_x(double x); 
double f_exp_x(double x); 
f_ptr fchoice(int i);
double integrate(double x0, double x1, double(*function_to_call)(double));

const int num_steps = 100;

int main()
{
    double x0(0.0), x1(1.0);
    int mychoice = 2;
    cout << "Integration Result: "
         << integrate(x0, x1, fchoice(mychoice)) << endl;
    return 0;
}

double f_sin_x(double x) {return sin(x);}
double f_exp_x(double x) {return exp(x);}

f_ptr fchoice(int i)
{
    if(i == 1) {return &f_sin_x;}
    else return &f_exp_x;
}

double f(int i, double x)
{
    if(i==1)
        return sin(x);
    else
        return exp(x);
}

double integrate(double x0, double x1, double(*function_to_call)(double))
{
    double dx = (x1 - x0)/num_steps; 

    double result = 0.0;
    for (int i = 0; i < num_steps; i++)
    {
        result += function_to_call(x0 + dx); 
    }

    return result;
}

这篇关于指向参数减少的函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆