今天一上午只编写了一个程序,求一个数的平方根!我们利用Newton迭代法求给定值的绝对值的平方根,下面给出Newton迭代法求平方根的算法过程:
①
设置猜测初值为1;
②
如果 |
猜测值*猜测值-X
|<ε,则转到④;(ε指的是一个很小的数)
③
设置新的猜测值为(X /
猜测值+猜测值)/
2,返回到②;
④
猜测值就是满足要求的X的平方根。
自己编写代码为:
#include<stdio.h>
#include<math.h>
float sqrt(float x);
void main()
{
float n,sqr;
char ch;
while(1)
{
printf("\n*****please input the number you want
to count!******** \n");
scanf("%f",&n);
if(n<0)
{
printf("\n***********************************************************
\n");
printf("the
input is :%f\n",n);
printf("the
input is a minus !\nso the number should be
converted to a plus\n then count the result
\n");
printf("\n***********************************************************
\n");
}
else
printf("the input is :%f\n",n);
sqr=sqrt(n);
printf("the sqr is :%f\n",sqr);
////////////////////////////////
ch=getchar();
printf("\n/////////////////////////////////////////////////////////////
\n");
printf("\n if you want to contine \n please enter
the Enter key!\n");
printf("\nif you want to quit! \nplease enter
others key \n");
printf("\n///////////////////////////////////////////////////////////
\n");
ch=getchar();
if(ch!='\n')
break;
}
}
float sqrt(float x)
{
float jingdu =1E-5;//设置精度
float sum=1.0;
while(1)
{
sum=(sum+fabs(x)/sum)/2.0;
if(fabs(sum*sum-fabs(x))<=jingdu)
break;
}
return sum;
}
加载中,请稍候......