Exercise -4- square root algorithm - Recursive / non-recursively

. 1 #include <stdio.h>
 2  
. 3  a float FABS ( a float X)
 . 4  {
 . 5      return X> = 0 X: (-? . 1 ) * X;
 . 6  }
 . 7  
. 8  a float sqrt1 ( a float A, a float P, a float E) // roots numbers a, p is a number of substantially similar root (can make p = a / 2), e is the result of tolerance (taken 0.00001) 
. 9  {
 10      the while (FABS (P * PA)> = E)
 . 11          = P (A + P / P) / 2 ;
 12 is      return P;
 13 is  }
 14 
15 float sqrt2(float a,float p,float e)//递归方式
16 {
17     if(fabs(p*p-a)<e)
18         return p;
19     else
20         return sqrt2(a,(p+a/p)/2,e);
21 }
22 
23 int main(int argc, char const *argv[])
24 {
25     printf("%f\n", sqrt1(88,44,0.0001));
26     printf("%f\n", sqrt2(44,22,0.0001));
27     return 0;
28 }

operation result:

 

Guess you like

Origin www.cnblogs.com/gilgamesh-hjb/p/11924177.html