高斯消元解线性方程组
warning:有bug待修
今天的线性代数课学了高斯消元解线性方程组,感觉很有意思,于是写了一个c语言小程序,功能如下:
1.把输入的矩阵经过初等变换,变成行阶梯形矩阵
2.判断方程组解的情况
3.如果有唯一解,输出方程组的解
实现的思路是枚举每一列,第i列从a[i+1][i]到a[m][i]依次用第i行消去。
1 #include <stdio.h> 2 double a[21][21], x[21]; 3 int m, n; 4 5 void print() { 6 printf("\n------->\n"); 7 for (int i = 1; i <= m; i++) { 8 for (int j = 1; j <= n; j++) printf("%.2lf ", a[i][j]); 9 printf("\n"); 10 } 11 } 12 13 void work() { 14 print(); 15 for (int j = 1; j <= n - 1; j++) { //从第一列到第n-1列 16 for (int i = j + 1; i <= m; i++) { //从第j+1行到第m行 17 if (a[j][i] == 0) continue; 18 double t = - a[i][j] / a[j][j]; 19 for (int k = j; k <= n; k++) a[i][k] += a[j][k] * t; 20 } 21 print(); 22 } 23 printf("\n----------已化为阶梯型矩阵----------\n\n"); 24 //判断是否有解 25 for (int i = 1; i <= m; i++) { 26 int flag = 0; 27 for (int j = 1; j <= n - 1; j++) { 28 if (a[i][j] != 0) flag = 1; 29 } 30 if (flag == 1 && a[i][n] == 0) { 31 printf("方程组无解\n"); 32 return; 33 } 34 } 35 //判断是否有无穷多解 36 if (m < n - 1) { 37 printf("方程组有无穷多组解\n"); 38 return; 39 } 40 else for (int i = 1; i <= m; i++) { 41 if (a[i][i] == 0) { 42 printf("方程组有无穷多组解\n"); 43 return; 44 } 45 } 46 //求解方程 47 printf("方程组有唯一解:\n"); 48 for (int i = m; i >= 1; i--) { 49 x[i] = a[i][n]; 50 for (int j = i + 1; j <= n - 1; j++) x[i] -= a[i][j] * x[j]; 51 x[i] /= a[i][i]; 52 } 53 for (int i = 1; i <= n - 1; i++) printf("x%d = %.2lf\n", i, x[i]); 54 } 55 56 57 int main() { 58 printf("请输入增广矩阵的行数和列数:\n"); 59 scanf("%d%d", &m, &n); 60 printf("请输入整个增广矩阵:\n"); 61 for (int i = 1; i <= m; i++) 62 for (int j = 1; j <= n; j++) 63 scanf("%lf", &a[i][j]); 64 work(); 65 return 0; 66 }
运行示例