线性方程组的直接解法

Posted shipeiyu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线性方程组的直接解法相关的知识,希望对你有一定的参考价值。

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <typeinfo.h>
using namespace std;

#define MAXN 50

int n;
double a[MAXN][MAXN];
double b[MAXN];
double m[MAXN][MAXN];
double x[MAXN];
int i, j, k;


void input() {
	cout <<"输入系数矩阵阶数n: ";
	cin >> n;
	cout <<"输入系数矩阵a:\n";
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			cout << "a[" << i << "][" << j << "]=";
			cin >> a[i][j];
		};
	cout <<".....................................\n";
	cout <<"请输入b矩阵:\n";
	for (int i = 1; i <= n; i++) {
		cout << "b[" << i << "]=";
		cin >> b[i];
	};
	cout << "线性方程组增广矩阵为:"<<endl; 
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			cout << setw(10);
			cout << a[i][j]<< setw(10);
		};
		cout << b[i]<<"  ";
		cout << endl;
	};
};


void PrintMiddle(int k) {
	printf("第%d次消元结果:\n", k);
	for (int i = 1;i <= n;i++) {
		for (int j = 1;j <= n;j++) {
			cout << setw(10) << a[i][j] << ‘ ‘;
		}
			cout << setw(10) << b[i] << ‘\n‘;
	};
};


void PrintRes() {
	cout << ".....................................\n";
	cout << "结果为:\n";
	for (int i = 1;i <= n; i++) {
		printf("x[%d]=  %lf\n", i, x[i]);
	};
};


void sge() {
	for (int k = 1;k < n; k++) {
		for (int i = k + 1;i <= n; i++) {
			m[i][k] = a[i][k] / a[k][k];
			for (int j = k + 1;j <= n;j++) {
				a[i][j] -= m[i][k] * a[k][j];
			};
		};
		for (int i = k + 1;i <= n;i++) {
			b[i] -= m[i][k] * b[k];
		};
		PrintMiddle(k);
	};
	x[n] = b[n] / a[n][n];
	for (int i = n - 1; i > 0; i--) {
		x[i] = b[i];
		for (int j = i + 1; j <= n; j++)
			x[i] -= a[i][j] * x[j];
			x[i] /= a[i][i];
	};
	PrintRes();
};


int main()
{
	while (true) {
		input();
		sge();
	};
    return 0;
}

  

以上是关于线性方程组的直接解法的主要内容,如果未能解决你的问题,请参考以下文章

99插值法,函数逼近,曲线拟和,数值积分,数值微分,解线性方程组的直接方法,解线性方程组的迭代法,非线性方程求根,常微分方程的数值解法

线性方程组的迭代解法——共轭梯度法

线性方程组的迭代解法——最速下降法

线性方程组的迭代解法——超松弛迭代法

线性方程组的迭代解法——雅可比迭代法

线性方程组的迭代解法——高斯-塞得勒迭代法