//二分法求方程的根
#include<iostream>
using namespace std;
float X_value(int n,float X)
{
//cout<<"X:"<<X<<endl;
if(0==n)
return 1.0;
else if(1==n)
return X;
return X*X_value(n-1,X);
}
float Get_value(float temp,int n,float A,float B,float C)
{
//get value of equation
//cout<<"temp:"<<temp<<endl;
//cout<<"次方值:"<<X_value(n,temp)<<endl;
//cout<<"值为:"<<A*X_value(n,temp)+B*temp+C<<endl;
return A*X_value(n,temp)+B*temp+C;
}
int getTimesOfDichotomy(float a,float b,float error)
{
// 求误差估计式中的k值,这里为i
float alpha;
alpha=error/(b-a);
float beta=1.0/(2*alpha);
//cout<<"beta:"<<beta<<endl;
for(int i=0;;i++)
{
if(X_value(i,2.0)>=beta)
{
return i;
}
}
}
int main()
{
/*
1.给定区间
2.给定误差范围
3.给定方程
*/
cout<<"The equation you should input is like this:"<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<"AX**n+Bx+C=0(A>0)"<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<"you could input a,n,b,c and section [a,b]"<<endl;
cout<<"--------------------------------------------"<<endl;
float A,B,C;
int n;
float a,b;
float error_rate;
cout<<"Please input value A:"<<endl;
cin>>A;
cout<<"Please input value n:"<<endl;
cin>>n;
cout<<"Please input value B:"<<endl;
cin>>B;
cout<<"Please input value C:"<<endl;
cin>>C;
cout<<"Please input pre-section value a:"<<endl;
cin>>a;
cout<<"Please input suf-section value b:"<<endl;
cin>>b;
cout<<"The error does not exceed:"<<endl;
cin>>error_rate;
float temp;
temp=(a+b)/2;
//cout<<"第一次temp:"<<temp<<endl;
int flag=-1;
//cout<<"方程为:"<<endl;
//cout<<A<<"x"<<n<<"+"<<B<<"x"<<C<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<"The times needed for dividing is:"<<getTimesOfDichotomy(a,b,error_rate)<<endl;
int times=getTimesOfDichotomy(a,b,error_rate);
while(++flag<times)
{
if(Get_value(a,n,A,B,C)<0&&Get_value(temp,n,A,B,C)<0)
{
a=temp;
temp=(a+b)/2;
//cout<<"1二分"<<flag+2<<"次的temp:"<<temp<<endl;
//cout<<"二分"<<flag+2<<"次的中间值:"<<Get_value(temp,n,A,B,C)<<endl;
}
else if(Get_value(a,n,A,B,C)<0&&Get_value(temp,n,A,B,C)>0)
{
b=temp;
temp=(a+b)/2;
//cout<<"2二分"<<flag+2<<"次的temp:"<<temp<<endl;
//cout<<"二分"<<flag<<"次的中间值:"<<Get_value(temp,n,A,B,C)<<endl;
}
else if(Get_value(a,n,A,B,C)>0&&Get_value(temp,n,A,B,C)>0)
{
a=temp;
temp=(a+b)/2;
//cout<<"3二分"<<flag+2<<"次的temp:"<<temp<<endl;
//cout<<"二分"<<flag<<"次的中间值:"<<Get_value(temp,n,A,B,C)<<endl;
}
else if(Get_value(a,n,A,B,C)>0&&Get_value(temp,n,A,B,C)<0)
{
b=temp;
temp=(a+b)/2;
//cout<<"4二分"<<flag+2<<"次的temp:"<<temp<<endl;
//cout<<"二分"<<flag<<"次的中间值:"<<Get_value(temp,n,A,B,C)<<endl;
}
}
cout<<"The equation ";
cout<<A<<"x"<<n<<"+"<<B<<"x"<<C<<" real root is:"<<temp<<endl;
cout<<"The value based on the root is:"<<Get_value(temp,n,A,B,C)<<endl;
system("pause");
return 0;
}
结果如下:
做的有点繁琐,还请见谅!!!