用c语言写一个高斯消元法求解函数代码
时间: 2024-05-03 21:20:51 浏览: 142
以下是一个用 C 语言实现高斯消元法求解线性方程组的示例代码:
```
#include <stdio.h>
#define N 3
void printMatrix(float matrix[N][N + 1]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N + 1; j++) {
printf("%.2f\t", matrix[i][j]);
}
printf("\n");
}
}
void gaussianElimination(float matrix[N][N + 1]) {
for (int k = 0; k < N; k++) {
// Find the row with the largest pivot
int maxRow = k;
for (int i = k + 1; i < N; i++) {
if (matrix[i][k] > matrix[maxRow][k]) {
maxRow = i;
}
}
// Swap the rows
for (int i = k; i < N + 1; i++) {
float temp = matrix[k][i];
matrix[k][i] = matrix[maxRow][i];
matrix[maxRow][i] = temp;
}
// Perform row operations
for (int i = k + 1; i < N; i++) {
float factor = matrix[i][k] / matrix[k][k];
for (int j = k + 1; j < N + 1; j++) {
matrix[i][j] -= factor * matrix[k][j];
}
matrix[i][k] = 0;
}
}
}
void backSubstitution(float matrix[N][N + 1], float solution[N]) {
for (int i = N - 1; i >= 0; i--) {
solution[i] = matrix[i][N];
for (int j = i + 1; j < N; j++) {
solution[i] -= matrix[i][j] * solution[j];
}
solution[i] /= matrix[i][i];
}
}
int main() {
float matrix[N][N + 1] = {
{ 2, 1, -1, 8 },
{ -3, -1, 2, -11 },
{ -2, 1, 2, -3 }
};
printf("Original matrix:\n");
printMatrix(matrix);
gaussianElimination(matrix);
printf("\nMatrix after Gaussian elimination:\n");
printMatrix(matrix);
float solution[N];
backSubstitution(matrix, solution);
printf("\nSolution:\n");
for (int i = 0; i < N; i++) {
printf("x%d = %.2f\n", i + 1, solution[i]);
}
return 0;
}
```
当然,这只是一个简单的示例,实际上高斯消元法还有很多细节需要注意,比如主元素不能为零,矩阵可能会奇异等。如果需要用到高斯消元法求解实际问题,建议使用已经成熟的数学库或者第三方库。
阅读全文