描述
![]()
要求前后两次求出的x的差的绝对值小于10-5.保留4位小数,并输出迭代的次数。
输入 2 输出 1.4142 3
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double a,x1,x2;
int i = 0; //用i来表示迭代的次数
cin >> a;
x1 = a / 2;
x2 = (x1 + a / x1) / 2;
while (fabs(x1 - x2) >= 0.00001)
{
x1 = x2;
x2 = (x1 + a / x1) / 2;
i++;
}
cout << fixed << setprecision(4) << x2 << " " << i << endl;
return 0;
}
该程序实现了一个计算平方根的算法,通过牛顿迭代法不断逼近精确值,直到x的前后两次求解差的绝对值小于10的负五次方。程序中输入一个数a,输出保留四位小数的平方根结果及迭代次数。
7277

被折叠的 条评论
为什么被折叠?



