你的支持是我最大的动力,你的意见是我前进的导航。
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! |
Author
Redow
|
Recommend
lcy
|
题目大意就是x∈[0, 100], Y∈[-10^10, 10^10],求8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 = Y 的解。
题目很简单,首先先需要些前期工作,通过一导,二导就会发现,其实对于 f(x) = 8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6, x∈[0, 100]时,这个函数是递增的。所以用二分法即可解题。
代码如下
1 #include <stdio.h> 2 #include <math.h> 3 double f (double x) //for convenience 4 { 5 return 8 * pow(x, 4) + 7 * pow(x, 3) + 2 * pow(x, 2) + 3 * x + 6; 6 } 7 int main() 8 { 9 int T; 10 double x1, x2, x3, y, y1, y2, y3; 11 scanf("%d", &T); 12 while(T--) 13 { 14 x1 = 0; 15 x2 = 100; 16 scanf("%lf", &y); //heed 17 y1 = f(x1) - y; 18 y2 = f(x2) - y; 19 if (y1 > 0 || y2 < 0) 20 printf("No solution!\n"); 21 else 22 { 23 while (fabs(y1 - y2) >= 0.0001) 24 { 25 x3 = (x1 + x2) / 2; 26 y3 = f(x3) - y; 27 if (y3 >= 0) 28 x2 = x3; 29 else 30 x1 = x3; 31 y1 = f(x1) - y; 32 y2 = f(x2) - y; 33 } 34 printf("%0.4f\n", x3); 35 } 36 } 37 return 0; 38 }
1 #include <stdio.h> 2 #include <math.h> 3 double f (double x) //for convenience 4 { 5 return 8 * pow(x, 4) + 7 * pow(x, 3) + 2 * pow(x, 2) + 3 * x + 6; 6 } 7 int main() 8 { 9 int T; 10 double x1, x2, x3, y, y1, y2, y3; 11 scanf("%d", &T); 12 while(T--) 13 { 14 x1 = 0; 15 x2 = 100; 16 scanf("%lf", &y); //heed 17 y1 = f(x1) - y; 18 y2 = f(x2) - y; 19 if (y1 > 0 || y2 < 0) 20 printf("No solution!\n"); 21 else 22 { 23 while (fabs(x1 - x2) >= 0.000001) 24 { 25 x3 = (x1 + x2) / 2; 26 y3 = f(x3) - y; 27 if (y3 >= 0) 28 x2 = x3; 29 else 30 x1 = x3; 31 } 32 printf("%0.4f\n", x3); 33 } 34 } 35 return 0; 36 }
注意点:
1、应该花大部分时间在思路上,编码应该快速完成
2、尽量用double,用double时,要注意用"%lf"输入。float 有38位,double有308位
3、这个题目要求x精确到4位,刚开始时,我以为我以x取到4位小数为结束条件,一直错!后来来发现应该以y1,y2很接近为结束结束条件。原因很简单以为x取到4位时,有可能这个y还很不精确。当然,也可以让x1和x2很接近,如上面的second program也是对的。
4、C中有fabs,pow,在math.h头文件中。