2016-08-05 69 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部分? –

相關問題