变步长梯形法求积分

函数f(x)=sinx/x,算法流程图如图:
在这里插入图片描述
C++代码如下:

/*
*1.给定函数f(x)=sinx/x
*2.给定区间[a,b]和精度e=0.005
*3.更新步长
*/
#include<iostream>
#include<math.h>
using namespace std;
double f(double x)
{
	if(x==0)
		return 1;
	return sin(x)/x;
}
int main()
{
	double a,b;//[a,b]
	double e;//accuracy
	cout<<"Please input section of [a,b]"<<endl;
	cout<<"-------------------------------"<<endl;
	cout<<"Please input pre-section a:"<<endl;
	cin>>a;
	cout<<"Please input suf-section b:"<<endl;
	cin>>b;
	cout<<"Please input an accuracy as e:"<<endl;
	cin>>e;
	double h;//step
	double T1;
	double T2;
	double S;
	double x;
	h=b-a;
	T1=0.5*h*(f(a)+f(b));
	S=0;
	x=a+0.5*h;
	S=S+f(x);
	x=x+h;
	if(x<b)
	{
		S=S+f(x);
		x=x+h;
	}
	else
	{
		T2=0.5*T1+0.5*h*S;
	}
	//e=T2-T1;
	while(fabs(T2-T1)>=e)
	{
		h=0.5*h;
		T1=T2;
		S=0;
		x=a+0.5*h;
		S=S+f(x);
		x=x+h; 
		while(x<b)
		{
			S=S+f(x);
			x=x+h; 
		}
		T2=0.5*T1+0.5*h*S;
	}
	cout<<"T2:"<<T2<<endl;
	cout<<"Hello Boker!"<<endl;
	system("pause");
	return 0;
}

结果如下:
在这里插入图片描述

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值