牛顿迭代法开方的过程如下:
(1)设置初始值为1
(2)如果|猜测值*猜测值-X|<E ,转到(4)
(3)设置新猜测值为(x/猜测值+猜测值)/2,返回(2)
(4)猜测值就是满足要求的x的平方根
#include <stdio.h>
float sqrt(float);
float fabs(float);
void main()
{
float FloatNum;
clrscr();
printf("Please enter a float number:");
scanf("%f",&FloatNum);
printf("Square_root of (fabs(%f)) = %f\n",FloatNum,sqrt(FloatNum));
}
/*牛顿迭代法求实数x的平方根*/
float sqrt(float x)
{
float EpsilonNum,GuessNum;
EpsilonNum = 1E-5;
GuessNum = 1.0;
while( fabs(GuessNum*GuessNum - fabs(x)) >= EpsilonNum )
{
GuessNum = (fabs(x)/GuessNum + GuessNum) / 2.0;
}
return(GuessNum);
}
/*求x的绝对值*/
float fabs(float x)
{
if( x < 0 )
{
x = -x;
}
return(x);
}
(1)设置初始值为1
(2)如果|猜测值*猜测值-X|<E ,转到(4)
(3)设置新猜测值为(x/猜测值+猜测值)/2,返回(2)
(4)猜测值就是满足要求的x的平方根
#include <stdio.h>
float sqrt(float);
float fabs(float);
void main()
{
float FloatNum;
clrscr();
printf("Please enter a float number:");
scanf("%f",&FloatNum);
printf("Square_root of (fabs(%f)) = %f\n",FloatNum,sqrt(FloatNum));
}
/*牛顿迭代法求实数x的平方根*/
float sqrt(float x)
{
float EpsilonNum,GuessNum;
EpsilonNum = 1E-5;
GuessNum = 1.0;
while( fabs(GuessNum*GuessNum - fabs(x)) >= EpsilonNum )
{
GuessNum = (fabs(x)/GuessNum + GuessNum) / 2.0;
}
return(GuessNum);
}
/*求x的绝对值*/
float fabs(float x)
{
if( x < 0 )
{
x = -x;
}
return(x);
}