-
Notifications
You must be signed in to change notification settings - Fork 0
/
GaussianElimination_modularization.c
111 lines (95 loc) · 2.9 KB
/
GaussianElimination_modularization.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <math.h>
#define MAX_SIZE 2 //未知数个数
void inputMatrix(double a[MAX_SIZE][MAX_SIZE + 1], int n);
void gaussianElimination(double a[MAX_SIZE][MAX_SIZE + 1], int n);
void backSubstitution(double a[MAX_SIZE][MAX_SIZE + 1], int n, double x[MAX_SIZE]);
void printMatrix(double a[MAX_SIZE][MAX_SIZE + 1], int n);
void printSolution(double x[MAX_SIZE], int n);
int main(void) {
double a[MAX_SIZE][MAX_SIZE + 1];
double x[MAX_SIZE];
inputMatrix(a, MAX_SIZE);
gaussianElimination(a, MAX_SIZE);
printMatrix(a, MAX_SIZE);
backSubstitution(a, MAX_SIZE, x);
printSolution(x, MAX_SIZE);
return 0;
}
//输入矩阵元素函数
void inputMatrix(double a[MAX_SIZE][MAX_SIZE + 1], int n) {
for (int i = 0; i < n; i++) {
printf("请输入第%d 行:", i + 1);
for (int j = 0; j < n + 1; j++) {
scanf("%lf", &a[i][j]);
}
}
}
// 高斯消元函数
void gaussianElimination(double a[MAX_SIZE][MAX_SIZE + 1], int n) {
for (int i = 0; i < n; i++) {
int f = 1;
int bj = 0;
double count;
double bs;
// 确保对角元素非零
if (a[i][i] == 0) {
f = 0;
for (int k = i + 1; k < n; k++) {
if (a[k][i] != 0) {
bj = k;
f = 1;
}
}
if (f == 1) {
// 交换行
for (int q = 0; q < n + 1; q++) {
count = a[bj][q];
a[bj][q] = a[i][q];
a[i][q] = count;
}
} else {
printf("Error: Diagonal element is zero, unable to perform Gaussian elimination.");
return;
}
}
// 消元
for (int k = i + 1; k < n; k++) {
bs = a[k][i] / a[i][i];
for (int j = 0; j < n + 1; j++) {
a[k][j] = a[k][j] - bs * a[i][j];
}
}
}
}
// 求解函数
void backSubstitution(double a[MAX_SIZE][MAX_SIZE + 1], int n, double x[MAX_SIZE]) {
for (int i = n - 1; i >= 0; i--) {
double count = a[i][n];
for (int j = i + 1; j < n; j++) {
count -= a[i][j] * x[j];
}
if (fabs(a[i][i]) < 1e-10) {
printf("Error: Singular matrix, back substitution not possible.");
return;
}
x[i] = count / a[i][i];
}
}
// 打印矩阵函数
void printMatrix(double a[MAX_SIZE][MAX_SIZE + 1], int n) {
printf("上三角矩阵为:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) {
printf("%.3lf ", a[i][j]);
}
printf("\n");
}
}
// 打印解函数
void printSolution(double x[MAX_SIZE], int n) {
printf("解为:\n");
for (int i = 0; i < n; i++) {
printf("x[%d]=%.3lf\n", i + 1, x[i]);
}
}