欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言笔记——用梯形法求定积分

程序员文章站 2024-02-02 21:52:52
...

   为求出总面积,先将区间【a, b】分成n小块,每一块的图形近似于一个小梯形。用梯形面积代替该小块图形的面积,然后进行累计,就能够得到曲线图形的近似面积。

#include <stdio.h>
#include <math.h>
#define MAXN 30
double fun1(double x);
double fun2(double x);
double fun3(double x);
double Definite_integral(double a, double b, double (*p)(double x));

main()
{
    double a, b;
    scanf("%lf %lf",&a,&b);
	printf("%lf\n",Definite_integral(a,b,fun2));
}
/* 梯形法求定积分*/
double Definite_integral(double a, double b, double (*p)(double x)){ 
	int i , n = MAXN;				
	double x, y1, y2, deta, f;		
	deta = (b-a)/n;
	x = a;
	y1 = (*p)(x);
	f = 0;
	for(i = 0;i < n;i++){
		x += deta;
		y2 = (*p)(x);
		f += (y1+y2)*deta/2;
		y1 = y2;
	}
	return f;
}
/*定义被积函数,三种供选择*/ 
double fun1(double x){
	double fx;
	fx = x;
	return fx;
}
double fun2(double x){
	double fx;
	fx = x*x*x+x*x+x+1;
	return fx;
}
double fun3(double x){
	double fx;
	fx = sin(x);
	return fx;
}