#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; }