编写程序,用牛顿切线法求方程f(x)= x^3⼀2+2x^2-8=0

2024-12-02 19:28:31
推荐回答(1个)
回答1:

#include"stdio.h"
#include"math.h"
int m;
float f(float x) /*求f(x)= x^3/2+2x^2-8的函数值*/
{
float y;
y=0.5*x*x*x-2*x*x-8;
return y;
}float f1(float x) /*求f(x)的导函数的值*/
{
float y;
y=1.5*x*x-3;
return y;
}float newton_dd(float x0,float e)
{
int i;
float p,p1,x;
for(i=1;;i++)
{
p=f(x0); /*牛顿迭代法的迭代式*/
p1=f1(x0);
x=x0-(p/p1);
printf("\nx=%f\n",x); /*输出每次迭代后的x的值*/
printf("x-x0=%f\n",x-x0); /*输出每次迭代后一个数与前一个数的差值*/
if(fabs(x-x0) break;
else
x0=x;
}
m=i;
return x;
}void main()
{
float d,x0,x;
printf("Input near root:x0="); //输入初值
scanf("%f",&x0);
printf("Input precision:e="); //输入精度
scanf("%f",&d);
printf("mei ci die dai hou x de zhi:\n");
printf("mei ci die dai x-x0 de cha zhi:\n");
x=newton_dd(x0,d);
printf("\nThe root of f(x)=0 is:x=%f\n",x);
printf("die dai ci shu:%d\n",m);
}