C++ Realization of Yacobi Iterative Method

You can find the formulas of the Jacobi equations on the Internet, and the C++ code implementation of the program is given here.

#include<iostream>
#include<math.h>
using namespace std;

//Jacobi迭代法求解方程组的解

int n;
double a[100][100], b[100], x[100][100];
double e;                                       //定义全局变量

void input()                                   //定义输入函数
{
	for (int i = 0;i < n;i++)
	{
		for (int j = 0;j < n;j++)               //输入系数矩阵
			cin >> a[i][j];
		cin >> b[i];                            //输入等式右边的矩阵
	}
}

void cau() {
	for (int k = 1;k <= 10;k++)
	{
		for (int i = 0;i < n;i++)
		{
			x[k][i] = 1.0 / a[i][i];          //先做一次除法运算
			double re = b[i];                 //每一行遍历完之后re重置
			for (int j = 0;j < n;j++)
			{
				if (j != i)
					re -= a[i][j] * x[k - 1][j];
			}
			x[k][i] *= re;                   //等re结果出来后再做一个乘法运算
		}
		for (int i = 0;i < n;i++)
			cout << x[k][i] << " ";cout << endl;      //输出第k次迭代结果
		bool judge = true;
		for (int i = 0;i < n;i++)
			if (fabs(x[k - 1][i] - x[k][i]) > e) {
				judge = false;break;
			}
		if (judge == true) return;
	}
}

int main()
{
	cout << "系数输入矩阵的阶数" << endl;
	cin >> n;
	cout << "请输入系数矩阵" << endl;
	input();
	cout << "请输入初始向量" << endl;
	for (int i = 0;i < n;i++) cin >> x[0][i];     //输入初始值
	cout << "输入求得的精度" << endl;
	cin >> e;
	cau();
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_42373896/article/details/121042073