游客 Signup | Login
中文 | En

1221 - C语言8.24

用牛顿迭代法求根。方程为ax3+bx2+cx+d=0,系数a、b、c、d的值由主函数读入。求此方程在输入的值k附近的一个实根,并由主函数输出。

Input

5个由空格隔开的实数,分别为a、b、c、d和k。保证方程一定有实根且在k附近。

Output

输出k附近的实根,保留4位小数。

请注意行尾输出换行。

Examples

Input

1 2 3 4 1

Output

-1.6506

Solution 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;
}

Solution 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;
}

Time Limit 1 second
Memory Limit 32 MB
Discuss Stats
上一题 下一题