题意:T组测试实例,每组输入Y,输出x:8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y。
思路:简单的二分法,首先编写函数实现输入x求得上式的值。然后二分法搜索下即可。
感想:最初写的那个程序总是超时,后来参照C进行了优化才过的,C里面有些东西还是值得借鉴的。
代码:留作检查超时错误~
#include<cmath>
#include<stdio.h>
using namespace std;
double f(double x)
{
double res=6.0,t=x;
res+=3*t;
t*=x;
res+=2*t;
t*=x;
res+=7*t;
t*=x;
res+=8*t;
return res;
}
int main()
{
int T,i=0;
double low=f(0.0),high=f(100.0),y;
scanf("%d",&T);
while(T--)
{
scanf("%lf",&y);
if(y<low||y>high)
{
printf("No solution!\n");
continue;
}
double l=0.0,r=100.0,mid,res;
while(l<r)
{
mid=(l+r)/2.0;
res=f(mid)-y;
if(fabs(res)<1e-10)
break;
if(res>0.0)
r=mid;
else
l=mid;
}
printf("%.4lf\n",mid);
}
return 0;
}