根的存在性定理(二分法)

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double f(double x)
{
    return x*x-3*x+1;
}
const double e=1e-9;
int main()
{
    double a,b,x;
    cin>>a>>b;          //a=2,b=3
    while(fabs(a-b)>=e)
    {
        double mid=(a+b)/2;
        if(f(mid)==0)
        {
            x=mid;
            break;
        }
        else if(f(a)*f(mid)<0)
        {
            b=mid;
            x=mid;
        }
        else
        {
            a=mid;
            x=mid;
        }
    }
    cout<<fixed<<setprecision(9)<<x<<endl;  //2.618033989
    //cout<<fixed<<setprecision(9)<<f(x)<<endl;//0.000000001
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/87971042
今日推荐