Problem C: 迭代法求平方根

版权声明: https://blog.csdn.net/t_jeey/article/details/79517702

Problem C: 迭代法求平方根

Time Limit: 1 Sec  Memory Limit: 128 MB

Description

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

Input

X

Output

X的平方根

Sample Input

4

Sample Output

2.000

HINT

参考答案:

#include<stdio.h>
#include<math.h>
int main()
{
	int x;
	float x1,x2;
	scanf("%d",&x);
	x1=(float)x/2;
	while(1)
	{
		x2=(x1+x/x1)/2;
		if(fabs(x1-x2)>=0.00001)
		{
			x1=x2;
			continue;
		}
		else
			break;
	}
	printf("%.3f",x2);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/t_jeey/article/details/79517702