数值计算刚学了牛顿迭代法求方程零点,今天正好看到POJ有关于这方面的题

这题水过·,关键要知道公式

g(x) = x – (x – A/x) / 2 根据这条公式迭代就可以

终止条件是前后两次迭代出来的值少于1e-6

 

#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
	int n;
	double x1, x2;
	int count;
	double err;
	//freopen("C:\\Users\\Haojian\\Desktop\\test.txt", "r", stdin);
	while (cin >> n)
	{
		x1 = 1;
		count = 0;

		do{
			x2 = x1 - (x1 - n/x1)/2;
			count++;
			err = abs(x2 - x1);
			x1 = x2;
		}while (err > 1e-6);

		cout << count << ' ' 
			<< setprecision(2)
			<< setiosflags(ios::fixed)
			<< x2 << endl;
	}
	return 0;
}

相关文章:

  • 2022-12-23
猜你喜欢
  • 2022-02-11
  • 2022-02-14
  • 2022-12-23
  • 2021-08-24
相关资源
相似解决方案