使用数组乘以矩阵?

时间:2015-05-19 02:02:46

标签: c++ arrays multidimensional-array

这是我一直在努力的任务。基本上我有核心思想和工作顺序的代码。但问题是我以不同于指令的方式做到了。

所以,要预先乘以我要求的数组矩阵(行,列)。然后我会再次询问数组的值。

但我想做的只是输入我的数组的值,并根据输入的整数自动查找数组的维数。但我不知道该怎么做,因为我认为我的导师说了一些关于无法将数组设置为变量值或类似的东西。

//what I'd like to be able to do
Enter the first matrix:
1 2 3
4 5 6

Enter the second matrix:
5 6
7 8
9 0

// what I am currently doing
#include<iostream>
using namespace std;
int main()
{
int l,m,z,n;
int matrixA[10][10];
int matrixB[10][10];
int matrixC[10][10];

cout<<"enter the dimension of the first matrix"<<endl;
cin>>l>>m;
cout<<"enter the dimension of the second matrix"<<endl;
cin>>z>>n;
if(m!=z||z!=m){
cout<<"error in the multiblication enter new dimensions"<<endl;
cout<<"enter the dimension of the first matrix"<<endl;
cin>>l>>m;
cout<<"enter the dimension of the second matrix"<<endl;
cin>>z>>n;
}

else{
cout<<"enter the first matrix"<<endl;
for(int i=0;i<l;i++){
for(int j=0;j<m;j++){
     cin>>matrixA[i][j];
     }
     }
cout<<"enter the second matrix"<<endl;
for(int i=0;i<z;i++){
for(int j=0;j<n;j++){
    cin>>matrixB[i][j];
}
}
for(int i=0;i<l;i++){
for(int j=0;j<n;j++){
        matrixC[i][j]=0;
        for(int k=0;k<m;k++){
matrixC[i][j]=matrixC[i][j]+(matrixA[i][k] * matrixB[k][j]);
}
}
}

cout<<"your matrix is"<<endl;
for(int i=0;i<l;i++){
for(int j=0;j<n;j++){
cout<<matrixC[i][j]<<" ";
}
cout<<endl;
}
}
//system("pause");
return 0;
}

2 个答案:

答案 0 :(得分:1)

您不能声明具有运行时维度的数组(在C中称为可变长度数组,允许它们),必须在编译时知道该维度。解决方案是使用标准容器,如std::vector

std::vector<std::vector<int>> matrix(M, std::vector<int>(N)); // M x N 

或使用动态数组,

int** matrix = new int*[M]; // allocate pointers for rows
for(size_t i = 0; i < N; ++i)
    matrix[i] = new int[N]; // allocate each row

然后不要忘记在程序结束时删除它们

for(size_t i = 0; i < N; ++i)
    delete[] matrix[i];
delete[] matrix;

您应该更喜欢std::vector方法,因为您不必处理内存分配等。

答案 1 :(得分:0)

从您的代码行开始,您似乎要求用户输入矩阵1的列和矩阵2的行的正确值。您使用的是if语句,它只运行一次。如果你的价值是&#34; m&#34;和&#34; z&#34;在第一个输入时不相等,那么你将永远无法进入代码的else部分,在那里你已声明其余的代码进入并乘以矩阵。

为了检查&#34; m&#34;的值和&#34; z&#34;是否相等,你可以使用while循环或do while循环。

while(m!=z)
{cout<<"enter the value m and z";`
cin>>m>>z;
}

除此之外,如果你使用l,m,z,n作为静态成员来保存内存将会很好。

如果您想声明所需尺寸的矩阵,那么您可以这样做。

首先,您要求用户输入矩阵的维度。 然后在输入正确尺寸后,您应该能够制作所需尺寸的矩阵。 这就是我想说的:

cout<<"enter the values of l and m";
cin>>l>>m;
cout<<"enter the values of z and n";
cin>>z>>n;
int array1[l][m];
int array2[z][n];

因此,您可以轻松输入所需矩阵的尺寸。