c++矩阵乘法不能产生正确的输出
C++ matrix multiplication not producing correct output
我试图在c++中乘以两个2D数组,但预期的输出是不正确的,以下是我的逻辑我正在尝试-
int A[l][m]; //creates A l*m matrix or a 2d array.
for(int i=0; i<l; i++) //This loops on the rows.
{
for(int j=0; j<m; j++) //This loops on the columns
{
A[i][j] = i+j; // Allocating values to A matrix
}
}
int B[m][n]; //creates B m*n matrix or a 2d array.
for(int i=0; i<m; i++) //This loops on the rows.
{
for(int j=0; j<n; j++) //This loops on the columns
{
B[i][j] = i+j+1; // Allocating values to B matrix
}
}
int C[l][n]; //creates C m*n matrix or a 2d array.
for(int i=0; i<l; i++) //This loops on the rows.
{
for(int j=0; j<n; j++) //This loops on the columns
{
for(int k=0; k<m; k++) //This loops on the columns
{
C[i][j] += A[i][k] * B[k][j]; // Allocating values to C matrix
//product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
}
cout << C[i][j] << " ";
}
cout << "n";
}
如果我让l=2 m=2 n =2我得到以下输出-
3
-107741472315 8
这是不正确的,谁能告诉我哪里错了
必须将C[i][j]
初始化为0。
或者你可以从0
开始求和,然后赋值给C[i][j]
:
//...
for(int j=0; j<n; j++) //This loops on the columns
{
int sum = 0;
for(int k=0; k<m; k++) //This loops on the columns
{
sum += A[i][k] * B[k][j]; // Allocating values to C matrix
//product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
}
C[i][j] = sum;
cout << C[i][j] << " ";
}
//...
你有未定义的行为: int C[l][n];
被声明但从未初始化。
通常,memset
用于将内存归零,或者只是循环遍历元素并将它们设置为零(使用现代编译器,速度一样快)。
您没有将c[i][j]初始化为0。使用
int c[2][2]= {{0}};
这将初始化数组的第一个元素。但是,如果初始化数组中的某些元素,则未初始化的元素将被设置为0。
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么Qt Creator的应用程序输出不能从spdlog记录器打印
- C 矢量不能输出
- cout 不能一致地打印字符串和变量值,导致输出未对齐
- 为什么我不能从输入文件中检索简单数据并使用C++将其写入输出文件?
- 为什么我的程序不能输出 i?
- 为什么这个向量不能给我与数组相同的输出?
- 为什么我不能输出迷宫的路径?谁能告诉我?请
- 为什么我不能在 QBS 项目中使用控制台输出?
- C++输出到Windows终端使用cout<<term_cc<color,default,attrib>在Windows上正确输出颜色和属性,但在Linux上不能
- 为什么程序不能立即输出?
- 为什么这个程序不能输出正确的异常?
- 为什么我不能通过管道传输两个 execl 调用的输出?
- 为什么采用向量的方法不能采用自己输出的返回向量?
- 为什么linux管道和标准输出不能一起工作
- 不能打开输出文件,没有这样的文件或目录
- 随机数(rand)不能输出未知字符
- Windows CMD不能正确输出UTF-16
- 在程序中不能得到正确的输出
- c++矩阵乘法不能产生正确的输出