- /*
- 矩阵的乘法 :规定 只有当第一个矩阵的列数等于第二个矩阵
- 的行数时,两个矩阵才能相乘. m*n矩阵 乘以n*k矩阵结果为一个m*k的矩阵
- */
- #include<iostream>
- using namespace std;
- void Dispaly(int a[][30],int row,int col); //矩阵元素显示函数
- void Input(int a[][30],int row,int col); //矩阵输入函数
- void Fuck(int sum[][30],int a[][30],int b[][30],int row,int col); //矩阵乘法
- int main()
- {
- int a[30][30];
- int b[30][30];
- int sum[30][30];
- int row1,col1,col2;
- while (1)
- {
- cout<<"请输入第一个矩阵的行和列数:";
- cin>>row1;
- cin>>col1;
- Input(a,row1,col1);
- cout<<"第二个矩阵的行数已为"<<col1<<",请在输入列数:"<<endl;
- cin>>col2;
- Input(b,col1,col2);
- cout<<"乘矩阵如下:"<<endl;
- Dispaly(a,row1,col1);
- cout<<"被乘矩阵如下:"<<endl;
- Dispaly(b,col1,col2);
- Fuck(sum,a,b,row1,col2);
- cout<<"两矩阵的乘积为:"<<endl;
- Dispaly(sum,row1,col2);
- }
- system("pause");
- return 0;
- }
- //////////////////////////////////////////
- void Input(int a[][30],int row,int col) //矩阵输入函数
- {
- int i,j;
- cout<<"请输入矩阵元素:"<<endl;
- for (i=0; i<row; i++)
- {
- for (j=0; j<col; j++)
- {
- cin>>a[i][j];
- }
- }
- }
- //////////////////////////////////////////
- void Dispaly(int a[][30],int row,int col) //矩阵元素显示函数
- {
- int i,j;
- for (i=0; i<row; i++)
- {
- for (j=0; j<col; j++)
- {
- cout<<a[i][j]<<" ";
- }
- cout<<endl;
- }
- }
- ////////////////////////////////////////////
- void Fuck(int sum[][30],int a[][30],int b[][30],int row,int col) //矩阵乘法
- {
- int i,j,h;
- int k = 0;
- int temp ;
- int mysum = 0;
- for (i=0; i<row; i++) //row 为乘矩阵的行数
- {
- for (j=0; j<col; j++) //col为被乘矩阵的列数
- {
- for (h=0; h<col; h++)
- {
- temp = a[i][h]*b[h][j]; //行乘以列
- mysum = mysum+temp; //行乘以列之和
- }
- sum[i][k] = mysum;
- mysum = 0;
- k++;
- if (k==col)
- {
- k = 0;
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/251220138221.html
来源: http://www.codesnippet.cn/detail/251220138221.html