这是一个解方程的程序。用的是高斯列主元消元法。
(在Visual C++.Net 2003 Windows Server 2003下调试成功)
目前没有检查是否有根。
// Gauss.cpp : 定义控制台应用程序的入口点。
//
//高斯列主元消元法
//2004-10-14
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "math.h"
#define M 3 //The Size of Matrix
int _tmain(int argc, _TCHAR* argv[])
{
//Definitions
double A[M][M];
double b[M];
double m[M][M];
double x[M];
int i;
int j;
int k;
int r;
double Temp;
double Max;
//Input the Matrix A
printf("Please Input the Matrix A:\n");
for (i=0;i
{
for (j=0;j
{
scanf( "%lf",&A[i][j]);
}
}
//End Input
//Input the Matrix b
printf( "Please Input the Matrix b:\n");
for (i=0;i
{
scanf( "%lf",&b[i]);
}
//End Input
//Solve the Matrix A
for (k=0;k
{
//Choose the Main Item
Max=abs(A[k][k]);
for (i=k;i
{
if (abs(A[i][k]) >Max)
{
Max=abs(A[i][k]);
r=i;
}
}
//End Choose
//Change the Row r and Row k
for (i=0;i
{
Temp=A[k][i];
A[k][i]=A[r][i];
A[r][i]=Temp;
}
Temp=b[k];
b[k]=b[r];
b[r]=Temp;
//End Change
//Calculate m
for (i=k+1;i
{
m[i][k]=A[i][k]/A[k][k];
A[i][k]=m[i][k];
}
//End Calculate
//Calculate Others
for (i=k+1;i
{
for (j=k+1;j
{
A[i][j]=A[i][j]-m[i][k]*A[k][j];
}
b[i]=b[i]-m[i][k]*b[k];
A[i][k]=0;
}
//End Calculate
}
//End Solve
//Solve the Result
x[M-1]=b[M-1]/A[M-1][M-1];
for (i=M-2;i >=0;i--)
{
Temp=0;
for (j=i+1;j
{
Temp=Temp+A[i][j]*x[j];
}
x[i]=(b[i]-Temp)/A[i][i];
}
//End Solve
//Output the Result
printf( "\nThe Result Matrix is:");
for (i=0;i
{
printf( "X%d=%lf\t",i+1,x[i]);
}
//End Output
getch();
return 0;
}
没有评论:
发表评论