迭代法求平方根

题目描述:

用迭代法求 。求平方根的迭代公式为: X[n+1]=1/2(X[n]+a/X[n]) 要求前后两次求出的得差的绝对值少于0.00001。 输出保留3位小数

输入:

a

输出:

a的平方根

代码实现:

#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);
}

输出:

猜你喜欢

转载自www.cnblogs.com/ttzz/p/8989508.html