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!
题意:
x∈[0, 100], Y∈[-10^10, 10^10],求8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 = Y 的解。
思路:
通过求导发现,f(x)是一个单调递增函数。即随着x的增大,y逐渐增大。成一个正比例的关系。所以可以采用二分法来解决此题。
注意:此题要求x精确到4位,我以为是要以x取到4位小数为结束条件,后来看了别人代码后发现是错的。此题应该以y1,y2很接近作为结束条件。原因:当x取到4位时,在4次方什么的会使y仍然很不精确。所以,直接索性让y取到4位保证更精确。如果讨论x的话,则应 取精确度更高的。
代码:
#include <cstdio>
#include <cmath>
double f (double x)
{
return 8 * pow(x, 4) + 7 * pow(x, 3) + 2 * pow(x, 2) + 3 * x + 6;
}
int main()
{
int T;
double x1, x2, x3, y, y1, y2, y3;
scanf("%d", &T);
while(T--)
{
x1 = 0;
x2 = 100;
scanf("%lf", &y);
y1 = f(x1) - y;
y2 = f(x2) - y;
if (y1 > 0 || y2 < 0)
printf("No solution!\n");
else
{
while (fabs(y1 - y2) >= 0.0001)
{
x3 = (x1 + x2) / 2;
y3 = f(x3) - y;
if (y3 >= 0)
x2 = x3;
else
x1 = x3;
y1 = f(x1) - y;
y2 = f(x2) - y;
}
printf("%0.4f\n", x3);
}
}
return 0;
}