1221 - C语言8.24
时间限制 : 1 秒
内存限制 : 32 MB
用牛顿迭代法求根。方程为ax3+bx2+cx+d=0,系数a、b、c、d的值由主函数读入。求此方程在输入的值k附近的一个实根,并由主函数输出。
题目输入
5个由空格隔开的实数,分别为a、b、c、d和k。保证方程一定有实根且在k附近。
题目输出
输出k附近的实根,保留4位小数。
请注意行尾输出换行。
输入/输出样例
输入格式
1 2 3 4 1
输出格式
-1.6506
C语言解答
#include<stdio.h> #include<math.h> float solve(float a,float b,float c,float d,float x); int main() { float a,b,c,d,k; scanf("%f%f%f%f%f",&a,&b,&c,&d,&k); printf("%.4f\n",solve(a,b,c,d,k)); return 0; } float solve(float a,float b,float c,float d,float x) { while(fabs(a*x*x*x+b*x*x+c*x+d)>0.000001) { x=x-(a*x*x*x+b*x*x+c*x+d)/(3*a*x*x+2*b*x+c); } return x; }
C++解答
#include <stdio.h> #include <math.h> int main() { float solve(float a, float b, float c, float d, float x); float a, b, c, d, k; scanf("%f%f%f%f%f", &a, &b, &c, &d, &k); printf("%.4f\n", solve(a, b, c, d, k)); return 0; } float solve(float a, float b, float c, float d, float x) { while (fabs(a * x * x * x + b * x * x + c * x + d) > 1e-6) { x = x - (a * x * x * x + b * x * x + c * x + d) / (3 * a * x * x + 2 * b * x + 3 * c); } return x; }