我有整個程序運行和完美工作,除了一項任務。 在我for循環中,當我嘗試打印我的product_matrix數組時,我得到一個額外的空間(「」),因爲我在每次迭代後都添加一個空格。二維數組中的最後一個空格;矩陣
我試過每個列和循環的if else參數,但我一直沒有運氣。一直呆在這部分幾個小時,我認爲是時候請專家幫忙。
Here is what it should look like and what program is doing instead
這裏是我的代碼:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
int first_matrix[10][10];
int second_matrix[10][10];
int product_matrix[10][10];
int column = 0, row =0;
int x = 0, y = 0, m = 0, n = 0;
string temp;
int value;
// putting user input into my first_matrix array.
cout << "Enter first matrix:" << endl;
while(true){
getline(cin, temp);
if (temp.length() == 0){
break;
}
stringstream ss(temp);
column = 0;
while (ss >> value){
first_matrix[row][column] = value;
column++;
}
row++;
}
// assigning length of cols and rows
x = row;
y = column;
// putting user input into my second_matrix array.
row = 0;
cout << "Enter second matrix:" << endl;
while(true){
getline(cin, temp);
if (temp.length() == 0){
break;
}
stringstream ss(temp);
column = 0;
while (ss >> value){
second_matrix[row][column] = value;
column++;
}
row++;
}
m = row;
n = column;
// checking if first and second matrix arrays have compatible dimensions.
if (y == m){
// multiplying first and second matrix and putting it into the product_matrix
for(row = 0; row < x; row++){
for (column = 0; column < n; column++){
product_matrix[row][column] = 0;
for (int k = 0; k < m; k++){
product_matrix[row][column] += (first_matrix[row][k] * second_matrix[k][column]);
}
}
}
//printing product_array.
cout << "The product is:" << endl;
for (row = 0 ; row < x; row++){
for (column = 0; column < n; column++){
cout << product_matrix[row][column] << " ";
}
cout << endl;
}
}
else
cout << "The two matrices have incompatible dimensions." << endl;
return 0;
}
也許不是最好的解決方案,但嘗試改變'COUT << product_matrix [行] [列] <<「「;''到COUT << product_matrix [行] [列] <<(列
DimChtz
這只是在列之後打印了1,最後一列之後是0打印 –