二分查找——B:Can you solve this equation? 解题报告

来源:互联网 发布:windows xp的外观设置 编辑:程序博客网 时间:2024/06/05 16:25

<span style="font-size:18px;"></span>
                                                                Can you solve this equation?
Description

现在,给出等式8* X^4+ 7* X^3+ 2* X^2+ 3 * X +6= Y,请找出他在0和100之间的解(包含0和100)。
现在,请你试试运气。。。。
 

Input

输入的第一行包含一个整数T(1 <= T <=100),表示测试用例的数目。接下来T个数字,每一行都有一个实数Y(abs(Y)<=10^10);

Output

对于每个测试用例,如果有解,你应该输出一个实数(精确到小数点后4位,四舍五入),如果在0到100之间无解,就输出“No solution!”。

Sample Input

2

100

-4 

Sample Output

1.6152

No solution!


解题思路:容易看出方程左边是一个单调递增函数,解在1~100之间,如果 y 小于 f(0) 或大于 f(100) 则无解。排除无解后,在0~100中用二分查找 f(x)=y.
<span style="font-size:18px;">#include <iostream>#include <math.h>#include <cstdio>#include <cmath>using namespace std;const double EPS=1e-5;//精度double y;double f(double x){    return 8*pow(x,4)+7*pow(x,3)+2*pow(x,2)+3*x+6;}double bs()//二分查找{    double lo=0,hi=100;    double mi;    while(1)    {        mi=(lo+hi)/2.0;//浮点数问题就别移位运算了        if(abs(f(mi)-y)<EPS)             return mi;        else if(y<f(mi))            hi=mi;        else            lo=mi;    }    return -1;}int main(){    int T;    cin>>T;    while(T--)    {        cin>>y;        if(y<f(0)||y>f(100))            cout<<"No solution!"<<endl;        else            printf("%.4lf\n",bs());    }    return 0;}</span>




0 0
原创粉丝点击