2017-09-03 31 views
-1

我是C++的一個小菜鳥,剛剛學習類。我正在創建一個程序,該程序使用允許我添加,減去,查找行列式以及3x3矩陣的逆的類。我的問題是,每當我編譯這個,它要求「輸入數據第一個數組....第二個數組」兩次!我不知道如何解決這個問題。此外,我想知道是否有人有任何提示這個決定性的和相反的部分!

這是我到目前爲止有:執行矩陣任務的C++類

#include<iostream> 
using namespace std; 

矩陣類:

class matrix { 


    int a[3][3], b[3][3]; 
    int add[3][3], sub[3][3]; 

    public: 
     matrix() 
     { 
      cout << "Enter data for first array:" << endl; 
      for(int i = 0; i < 3; i++) 
       for(int j = 0; j < 3; j++) 
        cin >> a[i][j]; 
      cout << "Enter data for second array:" << endl; 
       for(int i = 0; i < 3; i++) 
        for(int j = 0; j < 3; j++) 
         cin >> b[i][j]; 
     } 

     void addition() 
     { 
      cout << "After matrix addition" << endl; 
      for(int i = 0; i < 3; i++) 
      { 
       for (int j = 0; j < 3; j++) 
       { 
        add[i][j]= a[i][j] + b[i][j]; 
        cout << add[i][j] << "\t"; 
       } 
       cout << endl; 
      } 
     } 
     void subtraction() 
     { 
      cout << "After matrix subtraction" << endl; 
      for(int i = 0; i < 3; i++) 
      { 
       for(int j = 0; j < 3; j++) 
       { 
        sub[i][j] = a[i][j] - b[i][j]; 
        cout << sub[i][j] << "\t"; 
       } 
       cout << endl; 
      } 
     } 

}; 

主營:

int main() { 
    cout << "Calculations of matrix:" << endl; 
    matrix mtAdd = matrix(); 
    matrix mtSub = matrix(); 
    mtAdd.addition(); 
    mtSub.subtraction(); 
    return 0; 
} 
+1

只是一個提示,你可能應該使用'enum'或'static const'作爲表大小'3',而不是放在任何地方。 –

+0

我的建議是使用(或學習)已經有3x3矩陣實現的庫。我會強烈推薦Eigen3。 –

+0

您正在創建2個矩陣對象,每個對象包含4個數組a,b,add,sub ...您必須考慮哪些代碼應該是矩陣類的一部分,以及矩陣類之外應該做什麼。例如 - 每個矩陣類應該包含多少個數組? –

回答

0

原因是我們正在調用matrix()方法兩次,爲mtAdd和mtSub,而在main()m上聲明ethod。

int main() { 
cout << "Calculations of matrix:" << endl; 
matrix mtAdd = matrix(); 
matrix mtSub = matrix(); 
mtAdd.addition(); 
mtSub.subtraction(); 
return 0; 

}

嘗試調用它一次,並使用變量兩次(或你想要的很多次)。嘗試不同的方式。像這樣

int main() { 
cout << "Calculations of matrix:" << endl; 
matrix mtVar = matrix(); 
mtVar.addition(); 
mtVar.subtraction(); 
return 0; 

}

你應該提示一次。

+0

如何在不調用矩陣方法的情況下多次調用一個變量? – Drea

+0

嘗試只有一個像我現在編輯的變量聲明。檢查答案。 –