使用struct

时间:2016-05-25 03:48:06

标签: c++ c++11 matrix struct

我试图使用struct对两个矩阵求和,但它不起作用。

如果可以优化此代码,请告诉我:D

编译:

g++ -O2 -Wall program.cpp -o program

输出:

在/usr/include/c++/4.8/iostream:39:0中包含的文件中,                  来自Proy3.cpp:2: /usr/include/c++/4.8/ostream:548:5:注意:模板std :: basic_ostream& std :: operator<<(std :: basic_ostream&,const unsigned char *)      operator<<(basic_ostream& __out,const unsigned char * __s)      ^ /usr/include/c++/4.8/ostream:548:5:注意:模板参数扣除/替换失败: Proy3.cpp:51:30:注意:'std :: istream {aka std :: basic_istream}'不是从'std :: basic_ostream'派生的              cin<< &安培; M2.x [i] [j];

代码:

# include < cstdio >
# include < iostream >


typedef struct Matrix
{
    int row, column;
            int x[20][20];
};

Matrix M1,M2;

使用namespace std;

int main() {

cout << "Insert size rows: Mat[a]";
cin >> M1.row);

cout << "Insert size of columns Mat[a]";
cin >> M1.column;


cout << "Insert size of rows Mat[b]";
cin >> M2.row;

cout << "Insert size of columns Mat[b]";
cin >> M2.column;

int i, j;

   // Matrix x

    for(i = 0; i <= M1.row; i++)
{
        for(j = 0; j <= M1.column; j++)
        {
        cout << "Insert number for matrix X : \n";
        cin >> M1.x[i][j]
        }
}

       // Matrix y

    for(i = 0; i <= M2.row; i++)
{
        for(j = 0; j <= M2.column; j++)
        {
        cout << "Insert number for matrix Y : \n";
        cin << M2.x[i][j];
        }
}

// Matrix X + Matrix Y

for(i = 0; i <= M1.row; i++)
{
    for(j = 0; j < M1.column; j++)
    {
        cout <<"The sum of " << M1.x[i][j] << " + " <<  M2.x[i][j] << " = " << M1.x[i][j] +  M2.x[i][j] << endl;
    }
}
return 0;

}

2 个答案:

答案 0 :(得分:0)

  for(i = 0; i <= M2.M1.row; i++)
 {
    for(j = 0; j <= M2.M1.column; j++)
    {
    cout << "Insert number for matrix Y : \n";
    cin << &M2.M1.y[i][j];   
    }
  }

您尝试访问的M2.M1.y没有元素。 另外你为什么在M1内声明M2。你可能只有一个结构并有两个实例。像

struct matrix
{
    int row,column;
    int X[20][20];
};
struct matrix M1,M2;

现在您可以输入两个矩阵。

此外,您必须使用cin>>a代替cin>>&a

cin << &M2.x[i][j];也应该是

 cin >> M2.x[i][j];
    ^^^^

答案 1 :(得分:0)

我认为cin陈述应该是cin&gt;&gt; &安培; M2.x [i] [j];而不是cin&lt;&lt; &安培; M2.x [i] [j];