牛顿拉普森迭代法

 1 //计算某数的平方根 
 2   #include 
 3  
 4   float absoluteValue(float x)
 5   {
 6       if(x<0)
 7       {
 8           x=-x;
 9       }
10       return x;
11   } 
12  
13   //计算某数平方根的函数
14   float squareRoot(float x)
15   {
16       const float epsilon=.00001;
17       float guess=1.0;
18  
19       while(absoluteValue(guess*guess-x)>=epsilon)
20       {
21           guess=(x/guess+guess)/2.0; 
22       }
23       return guess; 
24   } 
25  
26   int main()
27   {
28       float num;
29       printf("输入要求平方根的数:");
30       scanf("%f",&num);
31       printf("%f平方根是%f\n",num,squareRoot(num));
32       return 0; 
33   }

 


你可能感兴趣的:(牛顿拉普森迭代法)