#include
#define MAX 50
using namespace std;
int chiedidimensione();
void Caricamento(int matr[MAX][MAX], int r, int c);
void Stampa(int matr[MAX][MAX],int r,int c);
void ProdottoMatrici(int M1[MAX][MAX], int M2[MAX][MAX], int r, int c2, int r2);
int main()
{
int r, c, r2, c2;
int mat1[MAX][MAX], mat2[MAX][MAX];
cout
r=chiedidimensione();
cout
c=chiedidimensione();
Caricamento(mat1, r, c);
cout
r2=chiedidimensione();
cout
c2=chiedidimensione();
Caricamento(mat2, r2, c2);
if (c==r2) {
ProdottoMatrici(mat1, mat2, r, c2, r2);
}
return 0;
}
int chiedidimensione()
{
int d;
do{
cin>>d;
}while(dMAX);
return d;
}
void Caricamento(int matr[MAX][MAX], int r, int c){
cout
for(int x=0; x
for(int y=0; y
cin>>matr[x][y];
}
}
cout
Stampa(matr,r,c);
}
void Stampa(int matr[MAX][MAX],int r,int c){
for(int x=0;x
for(int y=0; y
cout
}cout
}
}
void ProdottoMatrici(int M1[MAX][MAX], int M2[MAX][MAX], int r, int c2, int r2){
int M3[MAX][MAX];
for (int i = 0; i
for (int j = 0; j
M3[j] = 0;
for (int k = 0; k
M3[j] += M1[k] * M2[k][j];
}
cout
Stampa(M3, r, c2);
}
Domande da interrogazione
- What is the purpose of the `chiedidimensione` function in the code?
- How does the code ensure that matrix multiplication is possible?
- What is the role of the `ProdottoMatrici` function?
The `chiedidimensione` function is designed to prompt the user to input a dimension for the matrices, ensuring that the input is within a valid range (greater than 0 and less than or equal to MAX). It repeatedly asks for input until a valid dimension is provided.
The code checks if the number of columns in the first matrix (`c`) is equal to the number of rows in the second matrix (`r2`). This condition is necessary for matrix multiplication to be valid, and the multiplication is only performed if this condition is met.
The `ProdottoMatrici` function performs the multiplication of two matrices, `M1` and `M2`, and stores the result in a new matrix `M3`. It iterates through the rows and columns, calculating the dot product for each element in the resulting matrix, and then prints the resulting matrix using the `Stampa` function.