⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 trapezoid2a.cpp

📁 这是一个用梯形法求积的程序实例(VC)
💻 CPP
字号:
//Trapezoid method of Integration
//This is auto variable step version of c++

#include <iostream.h>
#include <math.h>
#include <iomanip.h>

const double eps=1.0e-8;

//-----------integrated fuction-------------
double f(double x)
{
	return exp(x)/(1+x*x);
}
//------------------------------------------

//-----------definite step version----------
double trapezoid(double a,double b,double (*f)(double))
{
	double h=(b-a);					//step
	double trap2=(f(a)+f(b))*h/2;	//current trapezoid
	double trap1=0.0;				//previous trapezoid

	int n=1;	//initial value
	int k=0;	//record the number of circulation

	while(fabs(trap2-trap1)>=eps)
	{
		trap1=trap2;

		double x=a-0.5*h;	//move backwards 1/2 step and then go continuously
		double sum=0.0;	//sum of variable step trapezoid
		for(int i=0;i<n;i++)
		{
			x+=h;
			sum+=f(x);
		}
		trap2=trap1/2.0 + sum*h/2.0;	
		//一半的积分值由上次保留的结果给出,另一半由变步长新值给出

		n+=n;
		h/=2;

		k++;
	}

	cout<<"Total: "<<k<<endl;
	return trap2;
}
//------------------------------------------

//-----------------main---------------------
void main()
{
	double x,y;
	
	cout<<"enter the lower limit,upper limit"<<endl;
	cin>>x>>y;

	cout<<"The Integration(T method): "<<setprecision(9)<<trapezoid(x,y,f)<<endl;
}
//------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -