要求前后两次求出的x的差的绝对值小于epson
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, x0, x, epson;
cout << "请输入a的值:";
cin >> a;
cout << "请输入epson的值:";
cin >> epson;
x0 = a / 2;
x = (x0 + a / x0) / 2;
while (fabs(x - x0)>epson)
{
x0 = x;
x = (x0 + a / x0) / 2;
}
cout << "平方根为:" << x << endl;
return 0;
}
运行结果: