#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double f(double);
double xpoint(double,double);
double root(double,double);
void main()
{
    double x1,x2,x,f1,f2;
    do                //输入两个不同点x1、x2，直到f(x1)和f(x2)异号为止
    {
      cout<<"please input x1,x2:"<<endl;
      cin>>x1>>x2;
      f1=f(x1);
      f2=f(x2);
    }
    while( (f1*f2) >0);
    x=root(x1,x2);
    cout<<setiosflags(ios::fixed)<<setprecision(6); //指定输出6为小数
    cout<<"a root of equation is:"<<x<<endl;
}
double f(double x)      //定义函数f，以实现f(x_1)=x^3-8x^2+12x+16
{
    return (x*x*x-8*x*x+12*x+16);
}
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)>=1e-6);
    return x;
}
