Problem 1018
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 172 Solved: 126
[ Submit][ Status][ Web Board]
Description
用迭代法求 。求平方根的迭代公式为: X[n+1]=1/2(X[n]+a/X[n]) 要求前后两次求出的得差的绝对值少于0.00001。 输出保留3位小数
Input
X
Output
X的平方根
Sample Input
4
Sample Output
2.000
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
float x1,x2,x;
cin>>x;
x1=x/2;
x2=(x1+x/x1)/2;
do
{
x1=x2;
x2=(x1+x/x1)/2;
}while(fabs(x1-x2)>=1e-5);
printf("%.3f",x1);
return 0;
}