变步长求积分.cpp

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

CPP
51
字号
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
double infe(double e,int n);
double f(double x);
int i;
double s,tn,t2n,x,h,a,b;
double infe(double e,int n)
{
	s=(f(a)+f(b))/2.0;
	h=(b-a)/n;
	x=a+h;
	for(i=1;i<=n;i++)
	{
		s=s+f(x);
		x=x+h;
	}
	t2n=s*h;
	do{
		tn=t2n;
		x=a+h/2.0;
		for(i=1;i<=n;i++)
		{
			s=s+f(x);
			x=x+h;
		}
		n=2*n;
		h=h/2.0;
		t2n=s*h;
	}while(fabs(t2n-tn)>e);
		return t2n;
}
double f(double x)
{
    double y;
	y=sin(x)/x;
	return y;
}

void main()
{
	double p,e;
	int n;
	cout<<"请输入区间的上限b,下限a,精度e和n的值:"<<endl;
	cout<<"a=";cin>>a;
	cout<<"b=";cin>>b;
	cout<<"e=";cin>>e;
	cout<<"n=";cin>>n;
	p=infe(e,n);
	cout<<"函数f(x)=sinx/x的变步长积分近似值为:"<<setprecision(8)<<p<<endl;
}

⌨️ 快捷键说明

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