1. 程式人生 > >hdu2199Can you solve this equation?(解方程+二分)

hdu2199Can you solve this equation?(解方程+二分)

Can you solve this equation?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 25633    Accepted Submission(s): 11018


Problem 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!

題意:知道y值,要求算出x。並且x只能在0~100之間,不然就輸出No solution!

題解:因為x只能在0~100之間。所以在知道y值得情況下判斷有沒有解的方法是:如果給出的Y值比f(0)還小,那他肯定沒有0~100之間的解。因為解在0~100之間都是正數。同理也不能大於f(100);

其實上面的可以用這個函式在0~100之間單調遞增來解釋,比較清楚

剩下的就是二分來找解,看一下程式碼還是挺容易理解的

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 double f(double x)
 4 {
 5     return (8*x*x*x*x+7*x*x*x+2*x*x+3*x+6);
 6  } 
 7 int main()
 8 {
 9     
10     int t;
11     while(~scanf("%d",&t))
12     {
13         while(t--)
14         {
15             double y;
16             scanf("%lf",&y);
17             if(f(0)>y||f(100)<y)
18             {
19                 printf("No solution!\n");
20                 continue;
21             }
22             double l,r;
23             l=0.0;r=100.0;
24             double mid=50.0;
25             while(fabs(f(mid)-y)>1e-5)
26             {
27                 if(f(mid)>y)
28                 {
29                     r=mid;
30                     mid=(l+r)/2.0;
31                     
32                 }
33                 else
34                 {
35                     l=mid;
36                     mid=(l+r)/2.0;
37                 }
38                 
39             }
40             printf("%.4lf\n",mid);
41         }
42     }
43     return 0;
44 }