用Gauss列主元素消去法求解方程组,用c++编程

方程组为 (1 2 1 -2 )(x1) (-1)
(2 5 3 -2 )(x2) (3)
(-2 -2 3 5 )(x3)= (15)
(1 3 2 5 )(x4) (9)
上面的不用了,问题改为
上三角为
(2 5 3 -2 )(X1) (3)
(0 3 6 3 )(X2) (18)
(0 0 0.5 -0.5)(X3)= (0.5)
(0 0 0 5 )(X4) (5)
用循环求出X1,X2,X3,X4(或者用最简单的办法求出来)

/*-----------------------------------
Description:
线性方程组的数值解法:
直接法的Gauss选主元消元法;
Environment:VC6
Date:13:34 2008-3-25
Author:[email protected]
-----------------------------------*/
#include <math.h>
#include <conio.h>
#include <stdio.h>
#define MAX 100

typedef struct{
int row,col;
float MAT[MAX][MAX];
float Solution[MAX];
}Matrix;

void Gauss(Matrix *M);
void MBack(Matrix *M);
void MSave(Matrix *M);
void MInput(Matrix *M);
void MOutput(Matrix *M);
void Solution(Matrix *M);
void MSort(Matrix *M,int n);

main()
{
Matrix Mat;
MInput(&Mat);
MSave(&Mat);
Gauss(&Mat);
MSave(&Mat);
if(Mat.row==Mat.col-1) {
MBack(&Mat);
Solution(&Mat);
}
printf("Press any key to halt...");
getch();
}

void MInput(Matrix *M)
{
int i,j;
printf("输入行数:"); scanf("%d",&M->row);
printf("输入列数:"); scanf("%d",&M->col);
for(i=0;i<M->row;i++){
printf("第%d行:",i+1);
for(j=0;j<M->col;j++){
scanf("%f",&M->MAT[i][j]);
}
}

for(i=0;i<M->row;i++)
M->Solution[i] = 0;
}

void MOutput(Matrix *M)
{
int i,j;
printf("MATRIX:\n");
for(i=0;i<M->row;i++){
for(j=0;j<M->col;j++)
printf("%10.3f",M->MAT[i][j]);
printf("\n");
}
printf("---END----\n");
}

void Gauss(Matrix *M)
{
int i,j,k;
float temp;
for(i=0;i<M->row-1;i++) {
MSort(M,i); MOutput(M);
for(j=i+1;j<M->row;j++) {
temp = M->MAT[j][i];
for(k=0;k<M->col;k++)
if(temp!=0) {
M->MAT[j][k] /= temp;
M->MAT[j][k] *= M->MAT[i][i];
M->MAT[j][k] -= M->MAT[i][k];
}
}
}
MOutput(M);
}

void MSort(Matrix *M,int n)
{
int i,j,k;
float temp[MAX];
for(i=n;i<M->row-1;i++) {
for(j=n;j<M->row-i-1;j++) {
if(fabs(M->MAT[j][n])<fabs(M->MAT[j+1][n])) {
for(k=0;k<M->col;k++) {
temp[k] = M->MAT[j+1][k];
M->MAT[j+1][k] = M->MAT[j][k];
M->MAT[j][k] = temp[k];
}
}
}
}
}

void MBack(Matrix *M)
{
int i,j;
float sum;
M->Solution[M->row-1] = M->MAT[M->row-1][M->col-1]
/
M->MAT[M->row-1][M->row-1];
for(i=M->row-2;i>=0;i--) {
sum = M->MAT[i][M->col-1];
for(j=i+1;j<M->row;j++)
sum -= M->MAT[i][j]*M->Solution[j];
M->Solution[i] = sum/M->MAT[i][i];
}
}

void Solution(Matrix *M)
{
int i;
printf("Solution:\n");
for(i=0;i<M->row;i++)
printf("X[%d] = %f\n",i+1,M->Solution[i]);
printf("\n---END---\n");
}

void MSave(Matrix *M)
{
int i,j;
FILE *eryar;
eryar = fopen("Matrix.txt","a");
fprintf(eryar,"--------BEGIN--------\n");
for(i=0;i<M->row;i++) {
for(j=0;j<M->col;j++)
fprintf(eryar,"%10.3f",M->MAT[i][j]);
fprintf(eryar,"\n");
}
fprintf(eryar,"[email protected]\n");
fclose(eryar);
}

/*---Test Data:--->
输入行数:3
输入列数:4
第一行:2 -1 3 1
第二行:4 2 5 4
第三行:1 2 0 7
Solution:
X[1]=9
X[2]=-1
X[3]=6
>---Test Data---*/
温馨提示:答案为网友推荐,仅供参考
相似回答