Can you solve this equation?(二分查找的简单应用)

Can you solve this equation?

Time Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u

Submit Status

Description

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

Input

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);
 

Output

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
 

Sample Output

     
     
     
     
1.6152 No solution!
 思路:
记f(x)为等式左边的值,如果f(100.0)小于Y或f(0.0)大于Y,无解,否则必有解,且解的范围为[0.0, 100.0],不断二分区间,直至找到f(x) = Y

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#define LL long long
#define MAXI 2147483647
#define MAXL 9223372036854775807
#define eps (1e-8)
#define dg(i) cout << "*" << i << endl;

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 y, low, high, mid;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%lf",&y);
        low = 0.0;
        high = 100.0;
        if(y > Solve(100.0) || y < Solve(0.0)) puts("No solution!");
        else
        {
            while(low + eps < high)
            {
                mid = (low + high) * 0.5;
                if(y > Solve(mid) + eps) low = mid;
                else if(y < Solve(mid) - eps) high = mid;
                else break;
            }
            printf("%.4lf\n", mid);
        }
    }
    return 0;
}


你可能感兴趣的:(Can you solve this equation?(二分查找的简单应用))