c++练习打卡(6)
牛顿迭代法求方程根
方程a*x*x*x+b*x*x+c*x+d=0,系数a,b,c,d都由主函数输入,求x在1附近的一个实根
x=x0-f(x0)/f"(x0),|x-x0|<=10^(-5)
流程图:

伪代码:
源代码:
#include<iostream>
#include<math.h>
int main (){
float solution(float a,float b,float c,float d);
float a,b,c,d,x;
scanf("%f %f %f %f",&a,&b,&c,&d);
x=solution(a,b,c,d);
printf("所求方程的根为x=%f",x);
}
float solution(float a,float b,float c,float d){
float x0,x=1.5,f,fd,h;
do{
x0=x;
f=a*x0*x0*x0+b*x0*x0+c*x0+d;
fd=3*a*x0*x0+2*b*x0+c;
h=f/fd;
x=x0-h;
}while(fabs(x-x0)>=1e-5);
return x;
}

浙公网安备 33010602011771号