高斯消元

 

Q 求 n 元 1 次线性方程组的解

1 。 先写出矩阵的增广矩阵

2 。 进行初等行变换,将左侧的矩阵变成单位矩阵,此时最右侧即是整个方程组的解

 

#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;

double a[10][10], del;
int n;

int solve(){
	for(int i = 1; i <= n; i++){
		int k = i;
		for(int j = i+1; j <= n; j++){
			if (fabs(a[j][i]) > fabs(a[k][i])) k = j;
		}
		if (fabs(del = a[k][i]) < eps) return 0;
		for(int j = i; j <= n+1; j++) swap(a[i][j], a[k][j]);
		for(int j = i; j <= n+1; j++) a[i][j] /= del;	
		for(int j = 1; j <= n; j++) {
			if (j == i) continue;
			del = a[j][i];
			for(int f = i; f <= n+1; f++) a[j][f] -= del*a[i][f]; 
		}
	}
	return 1;
}

int main () {
	int t;
	
	cin >> t;
	while(t--){
		n = 2;
		memset(a, 0, sizeof(a));
		for(int i = 1; i <= n+1; i++){
			for(int j = 1; j <= n; j++){
				scanf("%lf", &a[j][i]);
			}
		}
			
		int sign = solve();
		if (!sign) cout << "NO" << endl;
		else {
			for(int i = 1; i <= n; i++) printf("%.2lf\n", a[i][n+1]);
		}
		
//		for(int i = 1; i <= n; i++){
//    		for(int j = 1; j <= n+1; j++) printf("%.2lf%c", a[i][j], j==n+1?'\n':' ');
//		}
	}
		
	
	return 0;
}

/*
1
1 1
3 1
4 2
*/

 

posted @ 2019-01-16 19:28  楼主好菜啊  阅读(165)  评论(0编辑  收藏  举报