利用指向函数的指针作函数参数编写一个定积分的通用公式
求出以下2个函数的定积分∫(1+x)dx,∫(2x+3)dx
(上下限打不出,已省)
程序代码:
/*
功能:利用函數指針編寫一個通用的求定積分函數
*/
#include <stdio.h>
#include <math.h>
#include <conio.h>
double Get_Integral(double fun(double), double down_bound, double up_bound)
{
static const double interval = 0.0001;
double integral = 0;
for (double x = down_bound; x <= up_bound; x += interval)
{
integral += fun(x) * interval;
}
return integral;
}
double Fun1(double x)
{
return x;
}
double Fun2(double x)
{
return x * x;
}
double Fun3(double x)
{
return sin(x);
}
double Fun4(double x)
{
return cos(x);
}
int main(void)
{
double down_bound = -1;
double up_bound = 1;
double integral;
integral = Get_Integral(Fun1, down_bound, up_bound);
printf_s("Integral f(x)=x [%.4f, %.4f] = %.4f\n", down_bound, up_bound, integral);
integral = Get_Integral(Fun2, down_bound, up_bound);
printf_s("Integral f(x)=x^2 [%.4f, %.4f] = %.4f\n", down_bound, up_bound, integral);
integral = Get_Integral(Fun3, down_bound, up_bound);
printf_s("Integral f(x)=Sin(x) [%.4f, %.4f] = %.4f\n", down_bound, up_bound, integral);
integral = Get_Integral(Fun4, down_bound, up_bound);
printf_s("Integral f(x)=Cos(x) [%.4f, %.4f] = %.4f\n", down_bound, up_bound, integral);
_getch();
return 0;
}
