2016-03-04 63 views
0

我一直在研究一個程序來顯示兩個矩陣相減的結果。該程序允許用戶輸入矩陣的大小,然後提示用戶輸入這兩個矩陣的值。最後,程序應該單獨顯示這兩個矩陣,然後顯示兩者的相減結果。矩陣相減無盡顯示問題

當前代碼運行時,輸出只是數字的無盡顯示。我無法找到造成此問題的原因。我很感激任何有關導致此問題的原因。

謝謝!

using namespace std; 

#include <iostream> 
#include <conio.h> 

int main(){ 
    int i = 0, j = 0, n=0, a[10][10], b[10][10], c[10][10]; 
    bool positive = false; 

     cout << "Enter the size of the two - dimensional array: "; 
     cin >> n; 
     while (!positive){ 
      if (n >= 0){ 
       positive = true; 
      } 
      else { 
       cout << "Please enter a positive number for the size of the matrix."; 
       cin >> n; 
      } 
     } 
    cout << "Enter the values of the elements of array A" << endl; 
    for (i = 0; i < n; i++){ 
     for (j = 0; j < n; j++){ 
      cin >> a[i][j]; 
     } 
    } 
    cout << "Enter the values of the elements of array B" << endl; 
    for (i = 0; i < n; i++){ 
     for (j = 0; j < n; j++){ 
      cin >> b[i][j]; 
     } 
    } 
    cout << "Matrix A:" << endl; 
    for (i = 0; i < n; i++){ 
     for (j = 0; i < n; j++){ 

      cout << a[i][j] << " "; 
     } 
    } 
    cout << "Matrix B:" << endl; 
    for (i = 0; i < n; i++){ 
     for (j = 0; j < n; j++){ 

      cout << b[i][j] << " "; 
     } 
     cout << "\n"; 
    } 
    for (i = 0; i < n; i++){ 
     cout << endl; 
     for (j = 0; j < n; j++){ 
      c[i][j] = a[i][j] - b[i][j]; 

     } 
     cout << "\n"; 
    } 
    cout << "Matrix A - Matrix B: " << endl; 
    for (i = 0; i < n; i++){ 
     for (j = 0; j < n; j++){ 
      cout << c[i][j] << " "; 
     } 
     cout << "\n"; 
    } 
    return 0; 
} 
+3

這聽起來像你可能需要學習如何使用調試器來逐步通過你的代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

回答

1

大概這條線是造成麻煩的?

cout << "Matrix A:" << endl; 
for (i = 0; i < n; i++){ 
    for (j = 0; i < n; j++){ 

     cout << a[i][j] << " "; 
    } 
} 

更改j的for-loop(即,j < n)。看看是否有幫助..

+0

不能相信我錯過了!非常感謝! – AddieCaddy

+0

沒問題,這是一個常見的錯誤:)。爲了長遠的利益,請注意NathanOliver的建議 – Minh