#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn = 220;
typedef double Matrix[maxn][maxn];
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void Print(Matrix A, int n) {
for(int i = 0; i < n; i++) {
for(int j =0; j < n; j++)
cout << A[i][j] << " ";
cout << endl;
}
for(int i = 0; i < n; i++)
cout << " " << A[i][n] ;
cout << endl;
}
int Gauss(Matrix A, int n) { //计算方形矩阵
int i, j, k, r;
for(i = 0; i < n; i++) {
r = i; //选一行与第i行交换
for(j = i+1; j < n; j++)
if(fabs(A[j][i]) > fabs(A[r][i])) r = j;
if(r != i) for(j = 0; j <= n; j++) swap(A[r][j], A[i][j]);
if(A[r][k] == 0) return 0;
//与第i+1~n行消元
for(k = i+1; k < n; k++) {
double f = A[k][i] / A[i][i]; //为了让A[k][i] = 0
for(j = i; j <= n; j++) A[k][j] -= f*A[i][j];
}
}
for(i = n-1; i >= 0; i--) {
for(j = i+1; j < n; j++)
A[i][n] -= A[j][n]*A[i][j];
A[i][n] /= A[i][i];
}
return 1;
}
int main() {
Matrix B;
int n;
cin >> n;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cin >> B[i][j];
}
}
for(int i = 0; i < n; i++) {
cin >> B[i][n];
}
Gauss(B, n);
for(int i = 0; i < n; i++)
cout << " " << B[i][n];
return 0;
}
高斯消元法(普通列主元消元法)模板 ==》 还需要优化
最新推荐文章于 2023-07-24 18:50:40 发布