用C语言实现高斯消元法求解线性方程组
时间: 2024-01-21 11:04:33 浏览: 97
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
void print_matrix(double A[][MAX_SIZE], int n);
void print_vector(double b[], int n);
void print_solution(double x[], int n);
void gaussian_elimination(double A[][MAX_SIZE], double b[], int n);
int main()
{
int n;
double A[MAX_SIZE][MAX_SIZE], b[MAX_SIZE];
printf("Enter the size of the matrix: ");
scanf("%d", &n);
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%lf", &A[i][j]);
}
}
printf("Enter the elements of the vector:\n");
for (int i = 0; i < n; i++) {
scanf("%lf", &b[i]);
}
gaussian_elimination(A, b, n);
return 0;
}
void print_matrix(double A[][MAX_SIZE], int n)
{
printf("Matrix A:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%10.2f", A[i][j]);
}
printf("\n");
}
}
void print_vector(double b[], int n)
{
printf("Vector b:\n");
for (int i = 0; i < n; i++) {
printf("%10.2f\n", b[i]);
}
}
void print_solution(double x[], int n)
{
printf("Solution vector x:\n");
for (int i = 0; i < n; i++) {
printf("%10.2f\n", x[i]);
}
}
void gaussian_elimination(double A[][MAX_SIZE], double b[], int n)
{
double x[MAX_SIZE];
// forward elimination
for (int k = 0; k < n-1; k++) {
for (int i = k+1; i < n; i++) {
double factor = A[i][k] / A[k][k];
for (int j = k+1; j < n; j++) {
A[i][j] -= factor * A[k][j];
}
b[i] -= factor * b[k];
}
}
// backward substitution
x[n-1] = b[n-1] / A[n-1][n-1];
for (int i = n-2; i >= 0; i--) {
double sum = b[i];
for (int j = i+1; j < n; j++) {
sum -= A[i][j] * x[j];
}
x[i] = sum / A[i][i];
}
print_matrix(A, n);
print_vector(b, n);
print_solution(x, n);
}
阅读全文