简体   繁体   English

减少C中函数的参数数量

[英]reducing the number of arguments in functions in C

I want to do a numerical integration of a function f using the qtrap function defined in "Numerical recipes in C". 我想使用“ C的数字配方”中定义的qtrap函数对函数f进行数值积分。

double qtrap(double (*func)(double), double a, double b);

As shown, it is a 1-d integration of a variable of type double. 如图所示,它是double类型变量的一维积分。

But the function I want to integrate has an additional parameter a: 但是我要集成的函数有一个附加参数a:

double f(double x, int a)
{
    return a + x * x;
}

Now I am looking for a way to integrate f for different values of a. 现在,我正在寻找一种对a的不同值进行积分的方法。

My idea up to now: 到目前为止,我的想法是:

typedef double (*fctp1_t)(double);       //function pointer type for 1 arg
typedef double (*fctp2_t)(double, int);  //function pointer type for 2 args

int a = 10;
fctp1_t = f1d;
f1d = reduceArgument(f, a);

qtrap(f1d, 0, 1);

with the reduceArgument something like this: 使用reduceArgument这样的东西:

fctp1_t reduceArgument(fctp2_t f2d, int ia)
{
    return f2d(x, ia);
}    

This code results in the error: 'x' undeclared. 此代码导致错误:未声明'x'。

Thanks for any suggestions. 感谢您的任何建议。

C does not allow to build a function like that. C不允许构建这样的函数。 You have two way to solve your problem: 您可以通过两种方式解决问题:

  • modify qtrap so that it is able to handle a parametrized function; 修改qtrap,使其能够处理参数化函数;

  • use a global variable to pass the parameter implicitly. 使用全局变量隐式传递参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM