hdu2199 二分搜索

这是很简单的二分搜索;需要注意的是精度。一开始我用的是right-left<1e-4,测试样例中100我输出的最后一位为1,不合要求。

后来自己写了个四舍五入的一段,但交上去WA,于是改成1e-6,AC了。

代码题目如下:

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!
代码:
My code
 1 #include<stdio.h>
 2 #include<math.h>
 3 double equo(double a);
 4 int y,num;
 5 int main()
 6 {
 7     double left=0.0,right=100.0,mid=0;
 8     int ok=0,s;
 9     double an1,an2,an3,t;
10     scanf("%d",&num);
11     while(num--)
12     {
13         left=0.0;
14         right=100.0;
15         scanf("%d",&y);
16         an1=equo(left);
17         an2=equo(right);
18         while((an2-an1)>1e-6)
19         {
20             if(y<6||y>807020288)
21             {ok=1;break;}
22             mid=(left+right)/2;
23             an3=equo(mid);
24             if(an3*an1<0)
25             {
26                 an2=an3;
27                 right=mid;
28             }
29             else
30             {
31                 left=mid;
32                 an1=an3;
33             }
34         }
35         if((mid<0&&mid>100)||ok==1)printf("No solution!\n");
36          else 
37                  printf("%.4f\n",mid);
38     }
39     return 0;
40 }
41 double equo(double a)
42 {
43     double b;
44     b=8*pow(a,4)+7*pow(a,3)+2*pow(a,2)+3*a+6-y;
45     return b;
46 }

 

posted @ 2012-04-25 23:59  SmallMushroom  阅读(246)  评论(0)    收藏  举报