c语言求线性方程组组的解
时间: 2024-03-13 21:39:01 浏览: 93
线性方程组的编程求解
以下是三种C语言求解线性方程组的方法:
1. 一般的高斯消元解法
```c
#include <stdio.h>
#define MAX 100
void gauss(double a[MAX][MAX], double b[MAX], int n){
int i,j,k;
double factor, sum, x[MAX];
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
factor = a[j][i]/a[i][i];
for(k=i;k<n;k++){
a[j][k] -= factor*a[i][k];
}
b[j] -= factor*b[i];
}
}
for(i=n-1;i>=0;i--){
sum = 0;
for(j=i+1;j<n;j++){
sum += a[i][j]*x[j];
}
x[i] = (b[i]-sum)/a[i][i];
}
printf("The solution is:\n");
for(i=0;i<n;i++){
printf("x[%d] = %lf\n", i, x[i]);
}
}
```
2. Cholesky法求正定对称矩阵的线性方程组
```c
#include <stdio.h>
#include <math.h>
#define MAX 100
void cholesky(double a[MAX][MAX], double b[MAX], int n){
int i,j,k;
double l[MAX][MAX], y[MAX], x[MAX], sum;
for(i=0;i<n;i++){
for(j=0;j<=i;j++){
sum = 0;
if(j==i){
for(k=0;k<j;k++){
sum += l[j][k]*l[j][k];
}
l[j][j] = sqrt(a[j][j]-sum);
}
else{
for(k=0;k<j;k++){
sum += l[i][k]*l[j][k];
}
l[i][j] = (a[i][j]-sum)/l[j][j];
}
}
}
y[0] = b[0]/l[0][0];
for(i=1;i<n;i++){
sum = 0;
for(j=0;j<i;j++){
sum += l[i][j]*y[j];
}
y[i] = (b[i]-sum)/l[i][i];
}
x[n-1] = y[n-1]/l[n-1][n-1];
for(i=n-2;i>=0;i--){
sum = 0;
for(j=i+1;j<n;j++){
sum += l[j][i]*x[j];
}
x[i] = (y[i]-sum)/l[i][i];
}
printf("The solution is:\n");
for(i=0;i<n;i++){
printf("x[%d] = %lf\n", i, x[i]);
}
}
```
3. 追赶法解线性方程组
```c
#include <stdio.h>
#define MAX 100
void chase(double a[MAX], double b[MAX], double c[MAX], double d[MAX], double x[MAX], int n){
int i;
double p[MAX], q[MAX];
p[0] = -c[0]/b[0];
q[0] = d[0]/b[0];
for(i=1;i<n;i++){
p[i] = -c[i]/(a[i]*p[i-1]+b[i]);
q[i] = (d[i]-a[i]*q[i-1])/(a[i]*p[i-1]+b[i]);
}
x[n-1] = q[n-1];
for(i=n-2;i>=0;i--){
x[i] = p[i]*x[i+1]+q[i];
}
printf("The solution is:\n");
for(i=0;i<n;i++){
printf("x[%d] = %lf\n", i, x[i]);
}
}
```
阅读全文