c4-9.cpp

来自「这是和谭浩强的《c++程序设计》对应的教材例题chap4的程序」· C++ 代码 · 共 56 行

CPP
56
字号
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double root(double,double);
double f(double);
double xpoint(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);
 cout<<"A root of equation is "<<x<<endl;
 return 0;
}

double f(double x)
{
 double y;
 y=x*x*x-5*x*x+16*x-80;
 return y;
}

double xpoint(double x1,double x2)
{
 double y;
 y=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));
 return y;
}

double root(double x1,double x2)
{double x,y,y1;
 y1=f(x1);
 do
  {
   x=xpoint(x1,x2);
   y=f(x);
   if (y*y1>0)
    {y1=y;
     x1=x;
    }
   else
    x2=x;
  }while(fabs(y)>=0.000001);
 return x;
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?