gpt4 book ai didi

c++ - 在 C++ 中通过输入创建和填充矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 11:49:49 24 4
gpt4 key购买 nike

我正在尝试用 C++ 编写一个能够乘以矩阵的程序。不幸的是,我无法用 2 个 vector 创建矩阵。目标:我输入行数和列数。然后应该有一个用这些维度创建的矩阵。然后我可以通过输入数字来填充(例如 rows = 2 cols = 2 => Matrix = 2 x 2)矩阵。我用这两个代码试过了:(第二个在头文件中)

#include <iostream>
#include "Matrix_functions.hpp"

using namespace std;

int main ()
{
//matrices and dimensions
int rows1, cols1, rows2, cols2;
int **matrix1, **matrix2, **result = 0;

cout << "Enter matrix dimensions" << "\n" << endl;
cin >> rows1 >> cols1 >> rows2 >> cols2;

cout << "Enter a matrix" << "\n" << endl;

matrix1 = new int*[rows1];
matrix2 = new int*[rows2];

// Read values from the command line into a matrix
read_matrix(matrix1, rows1, cols1);
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;
}

这是主要代码。现在带有read_matrix函数的头文件:

#ifndef MATRIX_FUNCTIONS_H_INCLUDED
#define MATRIX_FUNCTIONS_H_INCLUDED

void read_matrix(int** matrix, int rows, int cols)
{
for(int i = 0; i < rows; ++i)
matrix[i] = new int[cols];

}

//int print_matrix(int result, int rows1, int cols1)
//{
// return 0;
//}

//int multiply_matrix(int matrix2, int rows2, int cols2, int matrix3, int rows3, int cols3, int result2)
//{
// return result2;
//}

#endif // MATRIX_FUNCTIONS_H_INCLUDED

第一部分有效。我可以填写尺寸。但随后它打印:输入一个矩阵,然后程序退出。为什么我无法填写矩阵的数字?

我希望有人能帮助我。如果有不清楚的地方,请告诉我。

提前致谢:D(不要注意大部分评论;那些是用于其余乘法代码的)

最佳答案

你忘记了 cin 数字,试试这个:

void 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];
}
}
}

关于c++ - 在 C++ 中通过输入创建和填充矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com