HDU-2199 Can you solve this equation?

http://acm.hdu.edu.cn/showproblem.php?pid=2199

学习方程求解用二分法。

注意1e-6而不是0;       

             Can you solve this equation?

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

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!
 
#include<stdio.h>
#include<math.h>
double y;
double cmp(double x)
{
	return 8*pow(x,4)+7*pow(x,3)+2*pow(x,2)+3*x+6;
}
double find()
{
	double mid;
	double a,b;
	a=0;b=100;
   while(b-a>1e-6)
   {
	     mid=(a+b)/2;
	   if(cmp(mid)<y)
          a=mid;
	   else
		  b=mid;
   }
    return (a+b)/2.0;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lf",&y);
      	if(cmp(0)<=y&&y<=cmp(100))
        printf("%.4lf\n",find());
        else
        printf("No solution!\n");
	}
	return 0;
}

 以前写的代码:

#include<stdio.h>
#include<math.h>
int main()
{
    int n,y,f;
    double x0,x1,x2,f1,f2,f0;
    scanf("%d",&n);
    while(n--)
    {
        x1=0;
        x2=100;
        scanf("%d",&y);
        f1=8*pow(x1,4)+7*pow(x1,3)+2*pow(x1,2)+3*x1+6-y;
        f2=8*pow(x2,4)+7*pow(x2,3)+2*pow(x2,2)+3*x2+6-y;
        if(f1*f2>0)
            printf("No solution!\n");
        else
        {
            do
            {
                x0=(x1+x2)/2;
                f0=8*pow(x0,4)+7*pow(x0,3)+2*pow(x0,2)+3*x0+6-y;
                if(f0*f1<0)
                {
                    x2=x0;
                    f2=f0;
                }
                else
                {
                    x1=x0;
                    f1=f0;
                }
            }while(fabs(f0)>1e-5);
            printf("%.4lf\n",x0);
        }
    }
    return 0;
}

 

posted @ 2013-11-24 20:00  疯狂的癫子  阅读(147)  评论(0编辑  收藏  举报