Iterative method to find square root

Topic description:

Find iteratively. The iterative formula for finding the square root is: X[n+1]=1/2(X[n]+a/X[n]) It is required that the absolute value of the difference obtained twice before and after is less than 0.00001. output to 3 decimal places

enter:

a

output:

square root of a

Code:

#include <stdio.h>
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
  float x,y;
  float a;
  cin>>a;
  y = 1.0;
  while(fabs(y-x)>0.00001){
      x = y;
      y = (x + a/x)/ 2 ;
  }
  printf("%0.3f\n",y);
}

output:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249408&siteId=291194637