变步长抛物线求积分.cpp

来自「用C++实现的多个算法」· C++ 代码 · 共 65 行

CPP
65
字号
#include<iostream.h>
#include<math.h>
#include<iomanip.h>

double a,b,e;
int n;
double simpson(double e,int n);
void main()
{
	double t;
	cout<<"请输入区间下限a,上限b,精度e的值:"<<endl;
	cout<<"下限 a=";
	cin>>a;
	cout<<"上限 b=";
	cin>>b;
	cout<<"精度 e=";
	cin>>e;
	cout<<"将曲间划分段数为 n=";
	cin>>n;
	t=simpson(e,n);
	cout<<"函数f(x)在区间["<<a<<","<<b<<"]上的积分为:"<<setprecision(9)<<t<<endl;
}
double f(double x)
{
	double y;
	y=4.0/(1.0+x*x);
	return y;
}

double simpson(double e,int n)
{
	int i;
	double s,sn,s2n,p,x,h;
	h=(b-a)/n;
	s=f(a)+f(b);
	i=1;p=0;x=a+h;
	while(i<=n-1)
	{
		if((i%2)!=0)
		{
			p=p+4.0*f(x);
			x=x+h;
		}
		else{
			s=s+2*f(x);
			x=x+h;
		}
		i++;
	}s=s+p;
	s2n=s*h/3.0;
	do{
		sn=s2n;
		x=a+h/2.0;
		s=s-p/2.0; p=0;
		for(i=1;i<=n;i++)
		{
			p=p+4.0*f(x);
			x=x+h;
		}
		s=s+p; n=n*2; h=h/2.0;
		s2n=s*h/3.0;
	}while(fabs(s2n-sn)>e);
	cout<<"总共运算的次数为:"<<i<<endl;
	return s2n;
}

⌨️ 快捷键说明

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