使用数组的矩阵乘法给了我错误的答案
matrix multiplication using arrays gives me wrong answer
我正在尝试将 3x4 和 4x2 矩阵相乘,然后将 3x2 矩阵输出到屏幕上。出于某种原因,我弄错了最后一行,但前两行是正确的。
我试过改变我的条件
int result[6];
int rows=3;
int columns = 2;
int mvalue=4;
但还是得到了错误的答案。
mvalue
应该是矩阵大小的中间值,在本例中为 4(3x 4 ×4x2(。
void multiMatrix(int matrix1[], int matrix2[], int result[], int rows, int columns, int mvalue){
for(int i=0; i<rows; i++){
for(int j=0; j<columns; j++){
result[i*columns+j]=0;
for(int w=0; w<mvalue; w++){
result[i*columns+j]= result[i*columns+j]+matrix1[i*columns+w]*matrix2[w*columns+j];
}
}
}
}
#include <iostream>
int main(){
int matrix1[]={1,2,3,4,
1,2,3,4,
5,4,5,3};
int matrix2[]={1,2,
3,4,
1,2,
3,4};
int result[6];
int rows=3;
int columns = 2;
int mvalue=4;
multiMatrix(matrix1, matrix2, result, rows, columns, mvalue);
for(int i=0; i<rows; i++){
for(int j=0; j<columns; j++){
std::cout<<result[i*rows+j]<<" ";
}
std::cout << std::endl;
}
}
输出应为:
22 32
22 32
31 48
我得到的实际输出是:
22 32
22 32
1 2
计算行应该是这样的:
result[i*columns+j] += matrix1[i*mvalue+w]*matrix2[w*columns+j];
此外,当您打印出值时,您应该打印出来
cout<<result[i*columns+j]<<" ";
而不是
cout<<result[i*rows+j]<<" "; // i * rows is squaring itself
您可以通过执行something * columns + something
来索引矩阵 1和矩阵2
这不可能是正确的,因为矩阵 1 和矩阵 2 具有不同的形状。在一种情况下,乘法应为 4,在另一种情况下应乘以 2。
我会让你从那里调试。
相关文章:
- 递归求和任务的错误答案
- 为什么我在代码厨师的 CMPRSS 问题中得到 WA(错误答案)?
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 寻找最小楼梯成本的动态规划问题的错误答案
- 为什么可变大小的数组会导致Codechef出现错误答案
- 如何修复此代码对几个测试用例的错误答案?
- 使用幂函数的计算给出了大数字的错误答案
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 二分法程序的错误答案(C++)
- 无法理解绘图程序中的错误答案
- C++ - 整数除以整数返回错误答案
- 布尔函数的错误答案
- SPOJ FASTFLOW上的错误答案
- 代码的错误答案是在Java Camel案件和C 下划线标识符之间转换的错误答案
- 200万以下所有素数的总和,线程给出错误答案
- 0-1整数背包返回错误答案(动态编程)
- UVa 在线判断 - 3n + 1 - 错误答案
- 提升C++原始算法错误答案
- 二项式系数函数C++错误答案 n>13
- 需要帮助以避免 SPOJ 上的"错误答案"