游客 Signup | Login
中文 | En

1313 - C语言程序设计教程(第三版)课后习题6.11

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

Input

X

Output

X的平方根

Examples

Input

4

Output

2.000

Solution C++

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int main()
{
	double a,x0,x1;
	cin>>a;
	x0=a/2;
	x1=(x0+a/x0)/2;
	while (fabs(x1-x0)>1e-5)
	{
		x0=x1;
		x1=(x0+a/x0)/2;
	}
	printf("%.3lf\n",x1);
	return 0;
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题