这是我今天上午帮同学做的一个小作业,拿出来交流交流。
可以直接下载源代码
怎么都是只下载不说话呢?大家可以随便谈谈自己的想法噻
下面这是源代码:
#include "stdafx.h"
#include "iostream.h"
#include "malloc.h"
int Row=0,Col=0;//矩阵总行数,总列数
double * InitMatrix()
{
double * matrix;
cout<<" 请输入矩阵维数(行,列):"<<endl;
cin>>Row>>Col;
matrix = (double*)malloc(Row*Col*sizeof(double));
double * Elem;
Elem = matrix;
cout<<" 请依次输入行列元素值:"<<endl;
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
{
cout<<" mat("<<i<<","<<j<<")=";
cin>>*Elem;
Elem++;
}
}
return matrix;
}
double GetElem(double * mat,int m,int n)
{
double *Elem = mat;
int i=0;
while(i<(m*Col+n))
{
Elem++;
i++;
}
return *Elem;
}
void SetElem(double * mat,int m,int n,double v)
{
double *Elem = mat;
int i=0;
while(i<(m*Col+n))
{
Elem++;
i++;
}
*Elem = v;
}
bool GaussJordan(double * mat)
{
if(1 != (Col-Row))
return false;
int i = 0,j = 0,k = 0;//行标,列标,第几轮计算
double L_ik = 1;
double L_kk = 1;//Elem(k,k)的倒数
double matElem = 0;
for(k = 0;k < Row;k++)
{
if(0 == GetElem(mat,k,k))
return false;
L_kk = 1/GetElem(mat,k,k);
for(i = 0;i < Row;i++)
{
if(i == k)
continue;
L_ik = GetElem(mat,i,k)*L_kk;
for(j = k+1;j < Col;j++)
{
matElem = GetElem(mat,i,j) - L_ik * GetElem(mat,k,j);
SetElem(mat,i,j,matElem);
}
}
//计算主行
for(j = k;j < Col;j++)
{
matElem = L_kk * GetElem(mat,k,j);
SetElem(mat,k,j,matElem);
}
}
//构造结果解矩阵
cout<<"计算结果如下:"<<endl;
for(i = 0;i < Row;i++)
{
cout<<"\t"<<GetElem(mat,i,Row);
}
return true;
}
int main(int argc, char* argv[])
{
double * mat = InitMatrix();
if(!GaussJordan(mat))
{
cout<<"错误!"<<endl;
}
cout<<endl;
return 0;
}