13.04.07 Can you solve this equation? (二分)

来源:互联网 发布:好听的网络音乐 编辑:程序博客网 时间:2024/06/15 19:40

Can you solve this equation?

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 87   Accepted Submission(s) : 18

Font: Times New Roman | Verdana | Georgia

Font Size:  

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

2100-4

Sample Output

1.6152No solution!
算法:
二分法
思路:
设top,bot,mid三个变量,并且写一个 f(x)的函数来代替上述方程,简化程序
先判断f(top)==0? f(bot)==0?
若都不为零,则进行二分
每次判断f(top)f(mid)>0? f(bot)f(mid)>0?
若前者小于零,则零点必然在[mid,top]中,则bot=mid,然后继续上述步骤,直到达到题目要求
若后者小于零,则零点必然在[bot,mid]中,则top=mid,然后继续上述步骤,直到达到题目要求
否则就不存在零点
代码:
#include<iostream>#include<cstdio>#include<cmath>double f(double x){    double t;    t=8*pow(x,4) + 7*pow(x,3) + 2*x*x + 3*x + 6;    return t;}using namespace std;int main (){    double x,y,top=100,bot=0,mid=50,ft,fb,fm;    int t;    bool find;    cin>>t;    while (t--)    {        find=true;        cin>>y;        top=100;        bot=0;        mid=50;        ft=f(top)-y;        fb=f(bot)-y;        fm=f(mid)-y;        if (ft==0)            printf("%.4lf\n",top);        else if (fb==0)            printf("%.4lf\n",bot);        else        {            while(fabs(fm)>1e-4)            {                ft=f(top)-y;                fb=f(bot)-y;                fm=f(mid)-y;                if (fb*fm<0)                {                    top=mid;                    mid=(top+bot)/2;                }                else                {                    bot=mid;                    mid=(top+bot)/2;                }                if (fabs(mid-100)<1e-4)                {                    find=false;                    break;                }            }            if (find==true)                printf("%.4lf\n",mid);            else                cout<<"No solution!"<<endl;        }    }    return 0;}
原创粉丝点击