题意:给你一个Y,问有没有一个x且0<=x<=100使得8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,保留四位小数输出
思路:很容易看出函数在[0,100]是单调递增的,所以Y < F(0) 和Y > F(100)这两种情况无解,有解的时候二分找X就可以
#include<bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
double Y;
double F(double x)//返回等号左边的值
{
return 8.0*pow(x,4) + 7.0*pow(x,3) + 2.0*pow(x,2) + 3.0*x + 6.0;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%lf", &Y);
if(Y < F(0) || Y > F(100)){ printf("No solution!\n"); continue; }//没答案的情况
double l = 0.0, r = 100.0, m = l + (r - l) / 2.0;
while(r - l > eps)
{
if(F(m) < Y) l = m + eps;
else if(F(m) > Y) r = m - eps;
else break;
m = l + (r - l) / 2.0;
}
printf("%.4lf\n",m);
}
return 0;
}
/*
2
100
-4
*/
来源:oschina
链接:https://my.oschina.net/u/4387051/blog/3216459