C++函数的嵌套调用和递归调用学习教程

2020-01-06 13:48:52刘景俊
  • double root(double, double); //函数声明  int main( ) 
  • {  double x1,x2,f1,f2,x; 
  • do  { 
  • cout<<"input x1,x2:";  cin>>x1>>x2; 
  • f1=f(x1);  f2=f(x2); 
  • } while(f1*f2>=0);  x=root(x1,x2); 
  • cout<<setiosflags(ios::fixed)<<setprecision(7);  //指定输出7位小数 
  • cout<<"A root of equation is "<<x<<endl;  return 0; 
  • }  double f(double x) //定义f函数,以实现f(x) 
  • {  double y; 
  • y=x*x*x-5*x*x+16*x-80;  return y; 
  • }  double xpoint(double x1, double x2) //定义xpoint函数,求出弦与x轴交点 
  • {  double y; 
  • y=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1)); //在xpoint函数中调用f函数  return y; 
  • }  double root(double x1, double x2) //定义root函数,求近似根 
  • {  double x,y,y1; 
  • y1=f(x1);  do 
  • {  x=xpoint(x1,x2); //在root函数中调用xpoint函数 
  • y=f(x); //在root函数中调用f函数  if (y*y1>0) 
  • {  y1=y; 
  • x1=x;  } 
  • else  x2=x; 
  • }while(fabs(y)>=0.00001);  return x; 
  • 运行情况如下:

     

     
    1. input x1, x2:2.5 6.7↙  A root of equation is 5.0000000