c++实现两个矩阵相乘

#include<iostream>
using namespace std;

int main()
{
	int m,n,k,i,j,p;
	int **a,**b,**c;
	cout <<"input the row of the first matrix size:";
	cin >>m;
	cout <<"input the column of the first matrix size and it is the row of the second matrix size:";
	cin >>n;
	cout <<"input the column of the second matrix size :";
	cin >>k;
	
	a= new int*[m];         //为第一个矩阵开辟内存
	for(i=0;i<m;i++)
		if((a[i]=new int[n])==NULL)
			exit(0);
		
		b= new int*[n];         //为第二个矩阵开辟内存
		for(i=0;i<n;i++)
			if((b[i]=new int[k])==NULL)
				exit(0);
			
			c= new int*[m];          //为存放结果的矩阵开辟内存
			for(i=0;i<m;i++)
				if((c[i]=new int[k])==NULL)
					exit(0);
				
				//输入两个矩阵的各个数据元素
				cout <<"input the numbers of the first matrix:";  
				for(i=0;i<m;i++)
					for(j=0;j<n;j++)
						cin>>a[i][j];
					cout <<"input the numbers of the second matrix:";
					for(i=0;i<n;i++)
						for(j=0;j<k;j++)
							cin>>b[i][j];
						
						//显示输入的两个矩阵
						for(i=0;i<m;i++)
						{
							for(j=0;j<n;j++)
								cout <<a[i][j]<<"\t";
							cout<<endl;
						}
						for(i=0;i<n;i++)
						{
							for(j=0;j<k;j++)
								cout <<b[i][j]<<"\t";
							cout<<endl;
						}
						
						
						//初始化存放结果的矩阵
						for(i=0;i<m;i++)
						{
							for(j=0;j<k;j++)
								c[i][j]=0;
						}
						
						//实现两个矩阵相乘
						for(i=0;i<m;i++)
						{
							for(j=0;j<k;j++)
							{
								for(p=0;p<n;p++)
								{
									c[i][j]+=a[i][p]*b[p][j];
								}
							}
						}
						
						
						//输出结果矩阵
						cout <<"the ji of the two juzhens is:"<<endl;
						for(i=0;i<m;i++)
						{
							for(j=0;j<k;j++)
							{
								cout<<c[i][j]<<"\t";
							}
							cout <<endl;
						}
						return 0;
}


 

  • 5
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值