In this assignment you are asked to write a program that reads in two matrixes of size n x m and s x t and then it outputs the resulting multiplication of those two matrixes. Since sizes of matrices are not known in advance, you need to implement a dynamic memory allocation scheme for matrices. Your program should prompt the user for n, m, s, t, and the elements of each matrix. After that, if the multiplication can be performed on the matrices, your program should output each matrix and the result of the matrix multiplication.
Recall that if the matrix A is of size n x m, and matrix B is of size m x t, the resulting matrix C would be of size n x t. However, if a matrix is n x m and the other is s x t, these matrices cannot be multiplied if m is not equal to s.
If you are not familiar with the matrix multiplication problem, study the following example in order to find a general solution for the multiplication of two-dimensional matrices. In this example, matrices A and B are of size 3 x 3. An entry Xij indicates an element X[i][j].
A00 A01 A02 B00 B01 B02
A = A10 A11 A12 B = B10 B11 B12
A20 A21 A22 B20 B21 B22
Resulting multiplication of the matrices A and B is equal to
A00 * B00 + A01 * B10 + A02 * B20 A00*B01 + A01 * B11 + A02*B21 A00*B02 + A01 *B12 + A02 *B22
C = A10 * B00 + A11 * B10 + A12 * B20 A10*B01 + A11 * B11 + A12*B21 A10*B02 + A11 *B12 + A12 *B22
A20 * B00 + A21 * B10 + A22 * B20 A20*B01 + A21 * B11 + A22*B21 A20*B02 + A21 *B12 + A22 *B22
To solve the problem, you need to determine how to obtain an entry, say C[i][k], from the entries of matrices A and B. Once you figure this out, the programming will be extremely easy task. Warning; before you start to program, test your solution.
矩阵相乘的问题,代码如下,如有帮助,请采纳一下,谢谢
#include <iostream>
using namespace std;
int main()
{
int m,n,s,t;
int i,j,k;
float** arr;
float** brr;
float** crr;
cout << "请输入矩阵A的大小m和n:";
cin >> m;
cin >> n;
cout << "请输入矩阵B的大小s和t:";
cin >> s;
cin >> t;
if(n != s)
{
cout << "n != s" << endl;
return 0;
}
cout << "请输入矩阵A:" << endl;
arr = new float*[m];
for (i=0; i < m;i++ )
{
arr[i] = new float[n];
for(j = 0;j < n;j++)
cin >> arr[i][j];
}
cout << "请输入矩阵B:" << endl;
brr = new float*[s];
for (i=0; i < s;i++ )
{
brr[i] = new float[t];
for(j = 0;j < t;j++)
cin >> brr[i][j];
}
crr = new float*[m];
for (i = 0; i < m;i++)
{
crr[i] = new float[t];
for (j = 0;j < t;j++)
{
crr[i][j] = 0;
for(k = 0; k < n; k++)
crr[i][j] += arr[i][k] * brr[k][j];
}
}
cout << "A*B=" << endl;
for (i = 0; i < m; i++)
{
for(j = 0;j < t;j++)
cout << crr[i][j] << " ";
cout << endl;
}
for (i = 0; i < m;i++)
{
delete[] arr[i];
}
delete[] arr;
for (i = 0; i < s;i++)
{
delete[] brr[i];
}
delete[] brr;
for (i = 0; i < m;i++)
{
delete[] crr[i];
}
delete[] crr;
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632