早教吧 育儿知识 作业答案 考试题库 百科 知识分享

编写程序:用迭代法求x=根号a。求平方根的迭代公式为Xn+1=1/2(Xn+a/Xn),要求前后两次求出的x的差的绝对值小于10的负5次方。

题目详情
编写程序:用迭代法求x=根号a。
求平方根的迭代公式为Xn+1=1/2(Xn+a/Xn),要求前后两次求出的x的差的绝对值小于10的负5次方。
▼优质解答
答案和解析
#include"stdio.h"
#include"math.h"
void main()
{
float x1=1,x2,a;
printf("input a\n");
scanf("%f",&a);
x2=a;
while(fabs(x1-x2)>=1e-5)
{
x1=x2;
x2=(x1+a/x1)/2;
}
printf("%f,%f",x1,x2);
}