HDU - 2199 Can you solve this equation?

问题描述:

Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.

输入说明:

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);

输出说明:

For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.

SAMPLE INPUT:

2
100
-4

SAMPLEOUTPUT:

1.6152
No solution!

思路:

题意很简单,给我们一个方程(注意这个方程是单调递增的),让我们求解x的值(精确到4位小数),最基础的二分了,只要定义一个起点-1和终点101,然后每次去起点和终点的和的一半进行比较,直到起点和终点的差值很小,然后输出此时的middle就可以了(我在这道题里精确到了1e-9,理论上要求精确到4位应该也是可以的)

AC代码:

#include <bits/stdc++.h>
using namespace std;
double solve(double x)//返回经过计算后的函数值
{
    
    
    return 8*x*x*x*x+7*x*x*x+2*x*x+3*x+6;
}
int main()
{
    
    
    int t;
    double n;
    double a,b,middle;
    cin>>t;
    while(t--)
    {
    
    
        cin>>n;
        double begining=-1.0;
        double ending=101.0;
        while(ending-begining>0.000000001)
        {
    
    
            middle=(ending+begining)/2;
            if(solve(middle)>=n)
                ending=middle;
            else
                begining=middle;
        }
        if(middle<0||middle>100)
        {
    
    
            cout<<"No solution!"<<endl;
        }
        else
        {
    
    
            cout<<fixed<<setprecision(4)<<middle<<endl;//注意精确的小数点位数
        }
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/m0_51727949/article/details/115175927
今日推荐