现在的位置: 首页 > 综合 > 正文

hdu2199Can you solve this equation? (浮点型二分查找)

2018年02月22日 ⁄ 综合 ⁄ 共 1202字 ⁄ 字号 评论关闭
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是一个单调递增的曲线,所以可以先把在[0,100]的x为整数位置的Y值求出,再N值的x位置确定在线段长度为1的段内,然后用浮点型的二分查找。
#include<stdio.h>
#include<math.h>
#define e 0.00000001
double y[105];
double yy(double i)
{
   return 8*pow(i,4.0)+7*pow(i,3.0)+2*pow(i,2.0)+3*i+6;
}
void cc()
{
    for(int i=0;i<=100;i++)
    y[i]=yy((double)i);
}
int two(double &v,double n)
{
    double l,r,mid;
    l=v-1;r=v;
    while(l+e<=r)//这里要加一个精度e
    {
        mid=(l+r)/2;
        if(yy(mid)==n)break;
        if(yy(mid)>n)r=mid;
        if(yy(mid)<n)l=mid;
    }
    v=mid;
    if(l<=r)return 1;
    return 0;
}
int main()
{
    int t,flog;
    double n,v;
    scanf("%d",&t);
    cc();
    while(t--)
    {
        scanf("%lf",&n);
        if(y[0]>n||y[100]<n)
        {
            printf("No solution!\n");
            continue;
        }
        for(int i=0;i<=100;i++)
        if(y[i]>=n)
        {
            v=(double)i; break;
        }
        if(v>0)
        flog=two(v,n);
        else flog=1;
        if(flog)
        printf("%.4f\n",v);
        else
        printf("No solution!\n");
    }
}

抱歉!评论已关闭.