در این مثال از آرایه های ثابت 20 * 20 استفاده شده ، بازم یاد آوری می کنم که من یه تازه کارم پس اگه ایراد یا پیشنهادی هست واقعا خوشحال می شم که مطرح بشه .
برنامه در Turbo C++ V3.0 DOS Full کاملا تست شده و با کمی تغییر در ++VC هم قابل استفاده هست .
//Multiply Two Matrix
#include <iostream.h>
#include <conio.h>
// function prototype
int getMat(int &, int &);
void fillMat(int, int, int[][20]);
void multiMat(int [][20], int, int,
int [][20], int, int,
int [][20], int &, int &);
void showMat(int [][20], int, int);
int main()
{
int aMat[20][20]={0},
bMat[20][20]={0},
rMat[20][20]={0},
aRow, aCol, bRow, bCol, rRow, rCol;
clrscr();
// Input Matrix a, b
cout<<"Enter number of Row & Column of Matrix A : ";
if (getMat(aRow, aCol))
{
cout<<"\nError : numbers must be greater than 0 !";
getch();
return 1;
}
cout<<"Enter number of Row & Column of Matrix B : ";
if (getMat(bRow, bCol))
{
cout<<"\nError : numbers must be greater than 0 !";
getch();
return 1;
}
// Test For Multiply
if (aCol != bRow)
{
cout<<"\nError : Can not multiply this matrixes !";
getch();
return 1;
}
// Fill Matrix a, b
cout<<"\n\nFill Matrix A\n---------------------\n";
fillMat(aRow, aCol, aMat);
cout<<"\n\nFill Matrix B\n---------------------\n";
fillMat(bRow, bCol, bMat);
// Multiply Matrix a , Matrix b
multiMat(aMat, aRow, aCol,
bMat, bRow, bCol,
rMat, rRow, rCol);
// Show Results
clrscr();
cout<<"Matrix A :\n---------------------\n";
showMat(aMat, aRow, aCol);
cout<<"\n\n\nMatrix B :\n---------------------\n";
showMat(bMat, bRow, bCol);
cout<<"\n\n\nMultiply A, B :\n---------------------\n";
showMat(rMat, rRow, rCol);
cout<<"\n\nPress Any Key ...";
getch();
return 0;
}
// Get Matrix Parameters : This function get and test parameters of input matrix .
int getMat(int &row, int &col)
{
cin>>row>>col;
if (row<=0)
return 1;
if (row>20)
return 1;
if (col<=0)
return 1;
if (col>20)
return 1;
return 0;
}
// Fill Matrix : This function fill matrix with input numbers .
void fillMat(int row, int col, int mat[][20])
{
for (int i=0; i<row; i++)
{
cout<<"Row "<<i+1<<" :\n";
for (int j=0; j<col; j++)
{
cout<<" Column "<<j+1<<" : ";
cin>>mat[i][j];
}
}
}
// Multiply Two Matrix : This function multiply two matrix
void multiMat(int aMat[][20], int aRow, int aCol,
int bMat[][20], int bRow, int bCol,
int rMat[][20], int &rRow, int &rCol)
{
int sum;
rRow = aRow;
rCol = bCol;
for (int i=0; i<aRow; i++)
for (int j=0; j<bCol; j++)
{
sum=0;
for (int k=0; k<aCol; k++)
sum += aMat[i][k] * bMat[k][j];
rMat[i][j] = sum;
}
}
// Show Matrix : This function show content of Matrix
void showMat(int mat[][20], int row, int col)
{
for (int i=0; i<row; i++)
{
cout<<endl;
for (int
j=0; j<col; j++)
{
cout.width(4);
cout<<mat[i][j];
}
}
}





پاسخ با نقل قول