我正在撰寫一個矩陣類,我需要在主程式中執行一些矩陣計算。我不確定為什么當用戶選擇大小超過 2x2 矩陣的矩陣時程式會突然結束。作業正常,std::cin直到兩行,但程式在回圈到達第三行后結束。下面僅顯示與我的問題相關的部分代碼。
#include<iostream>
#include <vector>
#include <cassert>
using std::vector;
using namespace std;
class Matrix {
private:
int rows;
int cols;
int **vtr;
public:
Matrix(int m = 2, int n = 2)
{
rows = m;
cols = n;
vtr = new int*[m];
for (int i = 0; i < m; i )
{
vtr[i] = new int [n];
}
for (int i = 0; i < m; i )
{
for (int j = 0; j < n; j )
{
vtr[i][j] = 0;
}
}
}
void read()
{
cout << "Enter the number of rows and columns of Matrix separated by a space: ";
cin >> rows >> cols;
Matrix a(rows, cols);
a.write();
for (int i = 0; i < rows; i )
{
for (int j = 0; j < cols; j )
{
cout << "(" << i << "," << j << ") : ";
cin >>vtr[i][j];
}
}
}
void write()
{
for (int i = 0; i < rows; i )
{
for (int j = 0; j < cols; j )
{
cout << vtr[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
}
};
int main()
{
Matrix A, B, C;
int row, column ;
cout << "For Matrix A" << endl;
A.read();
cout << "For Matrix B " << endl;
B.read();
cout << "For Matrix C" << endl;
C.read();
}
uj5u.com熱心網友回復:
由于 2D 陣列 vtr 在宣告 Matrix 物件時創建,您可以在讀取控制臺輸入后移動 vtr 創建,如下所示。
Matrix(int m = 2, int n = 2)
{
/*rows = m;
cols = n;
vtr = new int*[m];
for (int i = 0; i < m; i )
{
vtr[i] = new int [n];
}
for (int i = 0; i < m; i )
{
for (int j = 0; j < n; j )
{
vtr[i][j] = 0;
}
}*/
}
void read()
{
cout << "Enter the number of rows and columns of Matrix separated by a space: ";
cin >> rows >> cols;
vtr = new int*[rows];
for (int i = 0; i < rows; i )
{
vtr[i] = new int [cols];
}
//Matrix a(rows, cols);
//write();
for (int i = 0; i < rows; i )
{
for (int j = 0; j < cols; j )
{
cout << "(" << i << "," << j << ") : ";
cin >>vtr[i][j];
}
}
write(); //Prints the array
}
uj5u.com熱心網友回復:
當您定義矩陣 A、B、C 時,將構造三個矩陣。因此矩陣大小為 2x2。當您呼叫函式 cin 將值分配給不在 2x2 中的某個位置時將不起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488658.html
