将函数e^(-x)和e^(-x^2)传递到一个函数中,以便在C中进行计算
我必须编写一个程序,将函数将函数e^(-x)和e^(-x^2)传递到一个函数中,以便在C中进行计算,c,exp,C,Exp,我必须编写一个程序,将函数e^(-x)和e^(-x^2)传递到另一个名为calculateIntegral()的函数中,然后该函数将计算该函数的积分 限制: calculateIntegral()是一个函数,用于计算e^(-x)和e^(-x^2) 我只能传递函数、a和b边界以及间隔数作为函数calculateIntegral()的参数 我曾经考虑过在函数外部将x更改为-x,并将其分配给另一个变量以在e^(x)中进行计算,但随后我必须将其作为另一个参数包含在calculateIntegral(
e^(-x)
和e^(-x^2)
传递到另一个名为calculateIntegral()
的函数中,然后该函数将计算该函数的积分
限制:
是一个函数,用于计算calculateIntegral()
和e^(-x)
e^(-x^2)
- 我只能传递函数、
和a
边界以及间隔数作为函数b
的参数calculateIntegral()
x
更改为-x
,并将其分配给另一个变量以在e^(x)
中进行计算,但随后我必须将其作为另一个参数包含在calculateIntegral()
中
有没有办法改变原始的
e^(x)
,这样当它被传递到calculateIntegral()
中时,它将是e^(-x)
,所以rest函数只需将边界插入到该方程中进行计算?您想要的是参数化被积函数,因此,您希望能够传递函数,f
必须作为参数进行积分。在C中,这可以通过函数指针完成:
有关函数指针的更多详细信息,请查看您的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);