c语言 用迭代法求解

2024-12-16 06:43:26
推荐回答(3个)
回答1:

include
#include

int main()
{
double a;
double x2=0,x1=1.0;
printf("请输入被开方数:");
scanf("%lf",&a);
for(x1=1.0;fabs(x2-x1)>1e-10;)
{
x1=x2;
x2=(2*x1+a/(x1*x1*3.0));
}
printf("结果为:%f",x2);
return 0;
}

回答2:

#include
#include

int main()
{
double a;
double temp,xk2,xk1=0;
printf("请输入一实数:");
scanf("%lf",&a);
do{
xk2=(2*xk1+a/(xk1*xk1))/3.0; //Newton 法
temp=xk1;
xk1=xk2;
} while(fabs(xk2-temp)<1e-6)
return 0;
}

回答3:

#include
#include

double fun(double a, double x)
{
return x*x*x-a;
}

int main()
{
double a,i,j;
scanf("%lf",&a);
if(a==0) printf("%f\n",0.0);
else if(a>0)
{
i=0;j=1;
while(fun(a,j)<0)
{i=j;j*=2;}
}
else if(a<0)
{
i=-1;j=0;
while(fun(a,i)>0)
{j=i;i*=2;}
}
if(a!=0)
{
while(fabs(fun(a,(i+j)/2))>0.00001) // 二分法
{
if(fun(a,(i+j)/2)>0) j = (i+j)/2;
else if(fun(a,(i+j)/2)<0) i = (i+j)/2;
else
{
i = j = (i+j)/2;
break;
}
}
i = (i+j)/2;
printf("%f\n",i);
}
}