[Analysis]
Find the iterative formula of the square root: x1 = 1/2 × (x0 + a/x0).
algorithm steps are as follows:
(1) First set a initial value X0, as a square root value of A, and take A/2 as the initial value of the square root of A.
(2) Use the above iterative formula to find an X1 to substitute the new X1 into X0.
(3) Use the iterative formula again to find a new X1, compare X1 and X0. If their difference is less than the specified EPS (assuming 1E-6), the value is very close to the real square root. X1 can be possible As the approximate value of the square root; otherwise, the X1 will be substituted into X0, and the steps are continued (2) execution.
code:
#include <stdio.h>
#include <math.h>
#include <iostream>
#Define Eps 1E-6
void main ()
{{
double a, x0, x1;
Printf ("Please enter a real number:");
scanf ("%lf", & a);
if (A <0)
Printf ("Input error, please re -enter! \ n");
else
{{
x0 = A / 2;
x1 = (x0 + a / x0) / 2;
DO
{{
x0 = x1;
x1 = (x0 + a / x0) / 2;
} While (fabs (x0 -x1)> = EPS);
}
Printf ("%G's square root is:%g \ n", a, x1);
System ("pause");
}
Result: