【发布时间】:2019-09-27 15:24:36
【问题描述】:
我一直在尝试调试这段代码,但我不确定如何在我的 IDE 中实际访问位于动态分配内存中的值。该程序应该根据用户的输入初始化两个矩阵,然后尽可能将它们相乘。
我发现了一些错误并更正了它们,但我不确定是什么导致了这个问题。
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int main() {
int r1, c1, r2, c2;
do {
//GET DIMENSIONS OF MATRICIES
cout << "Welcome! This program takes two matricies and multiplies them together.\n"
<< "Enter the number of rows and number of columns for Matrix 1: ";
cin >> r1 >> c1;
cout << "Enter the number of rows and number of columns for Matrix 2: ";
cin >> r2 >> c2;
//DETECT IF MULTIPLICATION CAN HAPPEN
if (r1 != c2) {
cout << "Error: matricies cannot be multiplied. Please enter a new set.\n";
}
} while (r1 != c2); //have the user enter again if the rows and columns don't match
cout << endl;
//INTIALIZE MATRICIES USING DYNAMIC ARRAYS
//intialize MATRIX 1
IntArrayPtr *a = new IntArrayPtr[r1];
cout << "For MATRIX 1: Enter the contained values. Press enter after each entry.\n";
for (int i = 0; i < r1; i++) {
a[i] = new int[c1]; //init columns for each row
cout << "ROW" << i + 1 << "\n";
for (int j = 0; j < c1; j++) {
cin >> a[i][j]; //fill columns of rows
}
cout << endl;
}
//intialize MATRIX 2
IntArrayPtr *b = new IntArrayPtr[r2]; //init rows
cout << "For MATRIX 2: Enter the contained values. Press enter after each entry.\n";
for (int i = 0; i < r2; i++) {
b[i] = new int[c2]; //intialize columns
cout << "ROW" << i + 1 << "\n";
for (int j = 0; j < c2; j++) {
cin >> b[i][j]; //fill columns of rows
}
cout << endl;
}
//INITIALIZE MATRIX TO STORE RESULT IN
//matrix will have the rows of the first and columns of the second, according to matrix multiplication
IntArrayPtr *c = new IntArrayPtr[r1]; //init rows
for (int i = 0; i < r1; i++) {
c[i] = new int[c2]; //init columns
}
//MULTIPLY MATRICIES
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
//PRINT RESULT
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
cout << c[i][j] << " ";
}
cout << endl;
}
delete[] a; delete[] b; delete[] c;
system("pause");
return 0;
}
矩阵应该是乘法的结果,但是当我尝试使用小矩阵(例如 3 x 2 乘以 2 x 3)执行程序时,输出会吐出在我看来是垃圾的东西。我确信我的错误很愚蠢,但我们将不胜感激。
【问题讨论】:
-
听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs 和 Debugging Guide
-
不相关:你在你的唯一函数 (
main) 中的每个部分拥有的 cmets 可以被制成与你写为 cmets 的名称相似的函数。它有助于调试和重用类似的代码片段。您只需要一段代码来初始化矩阵,因此名为initialize_matrix的函数可能会起作用。 -
c[i][j] +=正在添加到c[i][j]但这些值从未初始化。 -
如果用new初始化,c[i][j]不应该为0吗?
-
@v78 C++ 很少会将您的对象归零。假设它不会,除非你知道它会的事实。这符合 C++ 设计的“不为不使用的东西付费”的目标。有时,当您
new某事时,您会立即为其分配一个有意义的值(就像您在初始化前两个矩阵时所做的那样)。如果new完成了将数组归零的工作,那么在这些情况下它将丢失工作。您需要为不需要的归零付费。
标签: c++