c语言 迭代法求平方根

2024-12-19 13:53:46
推荐回答(5个)
回答1:

#include
#include
void main( )
{
double x, y, y0 ;
printf( "输入一个正数:" ) ;
do
{
scanf("%lf", &x );//格式lf
}
while( x<0 );
y = 1;
do
{
y0 = y;
y = 1.0/2*( y + x / y ); //1.0变浮点数
}
while ( fabs( y - y0 ) / y > 0.00001);
printf("Square root of %lf is %lf\n", x, y ); //格式lf
}

回答2:

#include
#include

int main(int argc, int *argv[]) {
float x=1,x0;
int n;
printf("please intput a number:");
scanf("%d",&n);
while ( n < 0 )
{
scanf("%d",&n);
}

do
{
x0 = (x + n/x)/2;
if (abs(x0 - x) < pow(10,-5))
{
break;
}
else
{
x = x0;
}
} while (1);

printf("The square root of %d is %f\n",n,x0);
system("pause");
return 0;
}

回答3:

#include
#include
void main()
{
float x1,x2,a;
x2 = 1;
scanf("%f",&a);
x1=a/2;
while(fabs(x1-x2)>=1e-5)
{
x1=x2;
x2=0.5*(x1+a/x1);
}
printf("%f\n",x2);
}

回答4:

12345678910111213141516171819202122232425262728293031323334你的算法用的有问题 #include #include int main(void){ double a=0.0; double b=0.0; double c=1.0; double x;//---- const double e=0.00001; printf("input num:\n"); scanf("%lf",&a); getchar(); x=a; //负数时要进行处理 if ( a< 0 ) a=-a; c=1,b=a; while(fabs(c-b)>e) { c=b; b=0.5*(c+a/c); } if(x<0)//---- printf("sqrt(%lf) = %.3lfi\n",a,b); else printf("sqrt(%lf) = %.3lf\n",a,b); getchar(); return 0;}

回答5:

这个我不会