矩阵乘法不起作用
Matrix Multiplication doesn't work
本文关键字:不起作用 更新时间:2023-10-16
下面是我C++ 2 个矩阵相乘的代码。第一个输入是维度:所以矩阵 1 的行和列以及矩阵 2 的行和列。然后你需要输入两个矩阵的所有元素。完成后,应将 2 个矩阵相乘,并显示结果矩阵。但是,由于一个原因,在我输入所有元素后,它被卡住了。你们中有人明白我做错了什么吗?
#include <iostream>
#include "Matrix_functions.hpp"
using namespace std;
int read_matrix(int** matrix, int rows, int cols)
{
for(int i = 0; i < rows; i++)
{
matrix[i] = new int[cols];
for(int j = 0; j < cols; j++)
{
cin >> matrix[i][j];
}
}
return **matrix;
}
int print_matrix(int** result, int rows, int cols)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << result[i][j];
}
}
cout << endl;
return **result;
}
int multiply_matrix(int** matrix, int rows, int cols, int** matrix1, int rows1, int cols1, int** result)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols1; j++)
{
result[i][j] = 0;
for(int k = 0; k < cols; k++)
{
result[i][j] = result[i][j] + (matrix[i][k] * matrix1[k][j]);
}
}
}
return **result;
}
int main ()
{
//matrices and dimensions
int rows1, cols1, rows2, cols2;
int **matrix1, **matrix2, **result = 0;
cout << "Enter matrix dimensions" << endl;
cin >> rows1 >> cols1 >> rows2 >> cols2;
cout << "Enter a matrix" << endl;
matrix1 = new int*[rows1];
// Read values from the command line into a matrix
read_matrix(matrix1, rows1, cols1);
cout << "Enter a matrix" << endl;
matrix2 = new int*[rows2];
read_matrix(matrix2, rows2, cols2);
// Multiply matrix1 one and matrix2, and put the result in matrix result
multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);
print_matrix(result, rows1, cols2);
//TODO: free memory holding the matrices
return 0;
}
此外,现在,我的矩阵被打印为一维水平向量(1 2 3 4)而不是矩阵(1 2和3 4)。任何人都可以解释我如何解决这个问题?
multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);
`new` for result? Forgot?
像这样:
result = new int*[rows1];
for(int i = 0; i < rows1; i++)
{
result[i] = new int[cols2];
}
multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);
尚未为result
矩阵分配内存。
因此,您是未定义行为的受害者。
关于以矩阵形式打印,您需要打印换行符。
无需从读取和乘法函数返回元素。
另外,检查两个矩阵相乘的有效性,即乘法前cols1 == rows2
。
如果要将矩阵打印在不同的行上,请打印换行符。 执行此操作C++方法是使用 std::endl。
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << result[i][j];
}
cout << endl; ///< ADD THIS LINE
}
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- 我正在开发服务器,ip作为参数传递不起作用