函数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;
}
结果如下: