1

e^(-x)関数を とe^(-x^2)という別の関数に渡すプログラムを作成する必要がcalculateIntegral()あります。この関数は、関数の積分を計算します。

制限:

  • calculateIntegral()e^(-x)は、との両方の積分を計算するために使用される関数です。e^(-x^2)
  • functionの引数として渡すことができるのは、関数、aおよび境界、および間隔の数だけです。bcalculateIntegral()

xたとえば、関数の外側に変更して、-xそれを別の変数に割り当てて で計算することe^(x)を考えましたが、それを別の引数として に含める必要がありますcalculateIntegral()

元の を変更して、それが に渡されたときに、残りの関数が計算のためにその方程式に境界を差し込む必要があるようにする方法はありますe^(x)か?calculateIntegral()e^(-x)

4

1 に答える 1

3

必要なのは被積分関数をパラメーター化することなので、積分する必要がある関数をパラメーターとして渡すことができるようにする必要がfあります。C では、関数ポインタを使用してこれを行うことができます。

// IntegrandT now is the type of a pointer to a function taking a double and
// returning a double
typedef double (*IntegrandT)(double);

// The integration function takes the bound and the integrand function
double f(double min, double max, IntegrandT integrand)
{
    // here integrand will be called as if it were a "normal" function
}

// Your example functions
double minusExp(double x)
{
    return exp(-x);
}

double unitaryGaussian(double x)
{
    return exp(-x*x);
}

// now you can do
double res=f(-10, 10, minusExp);
double res2=f(-10, 10, unitaryGaussian);

関数ポインターの詳細については、C のマニュアルを参照してください。

于 2014-03-05T01:18:04.193 に答える