完整题干:
个人答案:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a;
double x1, x2;
cout<<"Please enter a: ";
cin>>a;
for (x1=1, x2=(x1+a/x1)/2; fabs(x2-x1)>1e-5; x1=x2, x2=(x1+a/x1)/2);
cout<<"Square root= "<<x2<<endl;
system("pause");
return 0;
}
结果:
参考答案:
#include<iostream>
using namespace std;
int main()
{
double a,x0,x1;
cout<<"请输入a的值\n";
cin>>a;
x0=a/2;
x1=(x0+a/x0)/2;
while (fabs(x0-x1)>=1e-5)
{
x0=x1;
x1=(x0+a/x0)/2;
}
cout<<a<<"的算术平方根为: "<<x1<<endl;
cout<<"sqrt()函数求得为: "<<sqrt(a);
system("pause");
return 0;
}