1 #include <stdio.h>
2
3 float fabs(float x)
4 {
5 return x>=0 ? x:(-1)*x;
6 }
7
8 float sqrt1(float a,float p,float e)//求根号a,p是根号a的大致近似(可以令p=a/2),e是结果允许误差(取0.00001)
9 {
10 while(fabs(p*p-a)>=e)
11 p=(p+a/p)/2;
12 return p;
13 }
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 }
运行结果:
原文:https://www.cnblogs.com/gilgamesh-hjb/p/11924177.html