二分法求根–c语言描述

二分法求根–c语言描述


#include 
#include 

double f(double x);
//求根主函数 x1 x2为求根区间!
void root(double x1,double x2);


int main()
{

 root(0,20);

 return 0;

}

double f(double x)
{
  return exp(x)-2;
}

void root(double x1,double x2)
{
 double x;
 int flag=0;
    while(fabs(f(x))>1E-6 && fabs(x1-x)>1E-6)
 {
   x=(x1+x2)/2;
   if(f(x)>0) x2=x;
   if(f(x)<0) x1=x;
   if(f(x)==0)
   {
    printf("Exactly root:%lf\n",x);
    flag=1;
   }
 }

 if(flag==0) printf("Not exat root or no root:%lf",x);


}

Leave a Reply

Your email address will not be published.