C语言,用迭代法求x=根号下a

2024-12-16 21:35:39
推荐回答(2个)
回答1:

float mysqrt(float a)
{
float x = a/2;
float d = 10000;
while ( d>1e-5 || d<-1e-5)
{
d = x;
x = (x + a/x) /2 ;
d -= x;
}
return x;
}

回答2:

#include
using namespace std;
int main()
{
double x=1000,a=1;
cout<<"a="; cin>>a;
do x/=2,x+=a/(4*x);
while (x/2-a/(2*x)>1e-5
|| x/2-a/(2*x)< -1e-5);
cout<< "sqrt("< <}