2017-09-03 28 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

尝试只有一个像我现在编辑的变量声明。检查答案。 –