【问题标题】:Addition of two matrix using struct使用结构添加两个矩阵
【发布时间】:2016-09-22 11:41:45
【问题描述】:

我正在尝试使用 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

代码:

# include < cstdio >
# include < iostream >


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

Matrix M1,M2;

使用命名空间标准;

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;

}

【问题讨论】:

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


    【解决方案1】:

    我认为cin语句应该是cin >> &M2.x[i][j];而不是 cin

    【讨论】:

      【解决方案2】:
        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 元素。 还有你为什么要在M2 中声明M1。你可以只有一个结构并有两个实例。类似

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

      现在你可以输入这两个矩阵了。

      您还必须使用cin&gt;&gt;a 而不是cin&gt;&gt;&amp;a

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

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

      【讨论】:

      • 好的,我进行了更改,但现在打印了很多:/usr/include/c++/4.8/ostream:530:5:注意:模板参数推导/替换失败:Proy3.cpp:51 :30: 注意:'std::istream {aka std::basic_istream}' 不是从 'std::basic_ostream' cin
      • 你不用cin&gt;&gt;&amp;a。你用cin&gt;&gt;a
      • 我进行了更改,但仍然得到相同的输出:/
      • omg... 哈哈哈,那个小错误.. 差点让我发疯 xD,非常感谢您的帮助和时间,感激不尽:D
      • 很高兴我能帮上忙。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 2016-04-25
      相关资源
      最近更新 更多