Description
用迭代法求 。求平方根的迭代公式为: X[n+1]=1/2(X[n]+a/X[n]) 要求前后两次求出的得差的绝对值少于0.00001。 输出保留3位小数
Input
一个非负数
Output
X的平方根
Sample Input
4.0
Sample Output
2.000
#include<stdio.h>
#include<math.h>
int main() {
double x1, x2;
float a;
scanf("%f", &a);//a即为题目中待求平方根的X
x2 = 1.0;
do {
x1 = x2;
x2 = (x1 + a / x1) / 2.0;
} while (fabs(x1 - x2) >= 0.00001);//若不符合要求就不断迭代
printf("%.3f", x2);//x2为符合要求的a的平方根的值
return 0;
}