HDU2199二分法求根

HDU2199Can you solve this equation?
y=8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6单调递增,所以直接二分法

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

double y;
double work(){
    double l=0,r=100;
    while(1){
        double mid=(l+r)/2;
        double value=8*mid*mid*mid*mid+7*mid*mid*mid+2*mid*mid+3*mid+6;
        if(fabs(value-y)<1e-5)return mid;//精度达到后返回mid值
        if(value<y)l=mid;
        else r=mid;
        if(mid<1e-5||100-mid<1e-5)return -1;//终止条件:mid逼近两端
    }
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%lf",&y);
        double ans=work();
        if(ans<0)printf("No solution!\n");
        else printf("%.4lf\n",ans);
    }
    return 0;
}

你可能感兴趣的:(HDU2199二分法求根)