除了一项任务外,我的整个程序都在完美运行。在for循环中,当我尝试打印product_matrix数组时,我会得到一个额外的空间("),因为我在每次迭代后都会添加一个空间。
我为循环的每一列和每一行尝试了if-else参数,但一直没有成功。就在这个地方被卡住了几个小时,我想是时候向专家寻求帮助了。
以下是它应该是什么样子,以及什么程序正在做
这是我的代码:
#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;
}
我会根据打印循环中的索引在换行符和空格之间进行选择:
for (row = 0 ; row < x; row++){
for (column = 0; column < n; column++){
cout << product_matrix[row][column];
cout << (column == n - 1) ? "n" : " ";
}
}
如果您在最后一列(n-1),此代码将打印一个换行符,并为所有其他列打印一个空格。使用此方法,在外循环中不需要cout << endl
。
如果你不熟悉
(condition) ? statement1 : statement1;
程序,这是一个简化的if-else。它相当于
if (condition) {
statement1;
} else {
statement2;
}