- //矩阵的乘法
- #include<iostream>
- #include <stdlib.h>
- void function();
- using namespace std;
- int main()
- {
- char choice;
- function();
- cout<<"输入“y”继续,输入“n”结束"<<endl;
- cin>>choice;
- system("cls");
- while(choice=='y')
- {
- function();
- cout<<"输入“y”继续,输入“n”结束"<<endl;
- cin>>choice;
- system("cls");
- }
- }
- void function() //乘法计算的函数
- {
- int m,n,p,q,x,y;
- int i,j,k;
- cout<<"请输入第一个矩阵的行数和列数:";
- cin>>m>>n;
- cout<<"请输入第二个矩阵的行数和列数:";
- cin>>p>>q;
- int a[m][n];
- int b[p][q];
- int c[m][q];
- if(n!=p) //判断是否符合矩阵相乘的条件
- {
- cout<<"无法相乘";
- exit(0);
- }
- cout<<"请输入第一个矩阵"<<endl; //矩阵输入
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- cin>>a[i][j];
- }
- }
- cout<<"请输入第二个矩阵"<<endl;
- for(i=0;i<p;i++)
- {
- for(j=0;j<q;j++)
- {
- cin>>b[i][j];
- }
- }
- for(i=0;i<m;i++) //三层循环进行运算
- {
- for(j=0;j<q;j++)
- {
- c[i][j]=0;
- for(k=0;k<n;k++)
- c[i][j]+=a[i][k]*b[k][j];
- }
- }
- cout<<"结果是:"<<endl;
- for(i=0;i<m;i++)
- {
- for(j=0;j<q;j++)
- {
- cout<<c[i][j]<<" ";
- }
- cout<<endl;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2012201615206.html
来源: http://www.codesnippet.cn/detail/2012201615206.html