哈哈哈
//二分法的实现
#include <iostream>
#include <math.h>
using namespace std;
void binary(double a,double b,double c);
double f(double x)
{
return (exp(x)+10*x-2);
}
int main()
{
double a,b,c;
cout<<"输入一个零点所在区间:(a,b):";
cin>>a>>b;
if(f(a)*f(b)>0)
{
cout<<"输入有误,请重新输入:";
cin>>a>>b;
}
cout<<"你选择的区间是: ("<<a<<","<<b<<")"<<endl;
cout<<"输入允许误差:";
cin>>c;
binary(a,b,c);
return 0;
}
void binary(double a,double b,double c)
{
int k=0;
double average;
while(b-a>c)
{
average=(a+b)/2;
if(f(a)*f( average)<0)
{
b= average;
}
else if (f(a)*f(average)>0)
{
a= average;
}
else
break;
k++;
}
cout<<"x的近似解为:"<<average<<" f(x)="<<f(average)<<" 循环次数:k="<<k<<endl;
}
/*void CXXXDlg::OnOK()
{
return;
}*/