2016-08-05 110 views
0

我有整个程序运行和完美工作,除了一项任务。 在我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; 
} 
+0

也许不是最好的解决方案,但尝试改变'COUT << product_matrix [行] [列] <<““;''到COUT << product_matrix [行] [列] <<(列 DimChtz

+0

这只是在列之后打印了1,最后一列之后是0打印 –

回答

1

我会根据您的打印循环索引换行符和空间之间进行选择:

for (row = 0 ; row < x; row++){ 
    for (column = 0; column < n; column++){ 
     cout << product_matrix[row][column]; 
     cout << (column == n - 1) ? "\n" : " "; 
    } 
} 

此代码如果你在最后一列(n-1),将打印一个换行符charatcer,并为所有其他列创建一个空格。使用此方法在外部循环中不需要cout << endl

如果你不熟悉的

(condition) ? statement1 : statement1; 

程序,这是一个简化的if-else。这相当于

if (condition) { 
    statement1; 
} else { 
    statement2; 
} 
+0

不幸的是,这并没有解决问题。 ): –

+0

它打印'#0#1 \ n#0#1 \ n' –

+0

当我尝试'cout <<(列== n - 1)? endl:''; '我得到一个错误:重载函数没有该行的上下文类型信息。你想看哪个代码声明?打印我的matrix_product部分? –