?? mymatrix.cpp
字號:
// myMatrix.cpp : Defines the entry point for the console application.
//
#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;
}
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -