【问题标题】:Multiply two matrices in C++在 C++ 中将两个矩阵相乘
【发布时间】:2014-08-11 18:40:37
【问题描述】:

我正在编写一个程序,它获取两个不同矩阵的元素,然后将它们相乘,然后将它们保存在一个多维数组中。 但它只适用于方阵。 (Visual Studio 2013 没有给出错误。) 如果你能帮我编辑这段代码以将每种矩阵相乘,我会很高兴。

    int a, b, c, d;
    int Mat1[10][10];
    int Mat2[10][10];
    int Mat3[10][10];
    Back1:
    cout << endl << "Enter the number of rows in Matrix 1 : ";
    cin >> a;
    cout << endl << "Enter the number of columns in Matrix 1 : ";
    cin >> b;
    cout << endl << "Enter the number of rows in Matrix 2 : ";
    cin >> c;
    cout << endl << "Enter the number of column in Matrix 2 : ";
    cin >> d;
    if (b != c) {
        cout << endl << "******************************************"
             << "\nThis type of Matrix can't be multiplied . " << endl;
        goto Back1;
    }
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            cout << endl << "(MAT 1 ) \n\nEnter the Element of row " << i + 1
                 << " column " << j + 1 << " : ";
            cin >> Mat1[i][j];
        }
    }
    for (int i = 0; i < c; i++) {
        for (int j = 0; j < d; j++) {
            cout << endl << "(MAT 2 ) \n\nEnter the Element of row " << i + 1
                 << " column " << j + 1 << " : ";
            cin >> Mat2[i][j];
        }
    }
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < d; j++) {
            Mat3[i][j] = Mat1[i][j] * Mat1[i][j];
        }
    }
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < d; j++) {
            cout << setw(4) << Mat3[i][j] << setw(4);
        }
        cout << endl;
    }
}

【问题讨论】:

  • 如果您指的是矩阵乘法的正常数学定义,那么您的代码是错误的。您至少需要一个内部for 循环来总结元素产品。
  • 您可以缩进/格式化您的代码,并创建子函数以提高可读性。
  • 请缩进你的代码,使用空格而不是制表符,通常使用 4 级缩进(但只要一致,几乎任何缩进都可以)。 VS 2010 是否支持 VLA——可变长度数组?如果没有,您将不得不模拟它们,这有点痛苦。
  • 拜托,不需要goto。只需使用do-whilebool matrixOK=false; do { ... if (b == c) matrixOK=true; } while (!matrixOK);

标签: c++ visual-c++ c++11


【解决方案1】:

您的矩阵乘法代码是错误的。而不是:

for (int i = 0; i < a; i++)
{
   for (int j = 0; j < d; j++)
   {
      Mat3[i][j] = Mat1[i][j] * Mat1[i][j];
   }
}

你需要:

for (int i = 0; i < a; i++)
{
   for (int j = 0; j < d; j++)
   {
      Mat3[i][j] = 0;
      for (int k = 0; k < c; k++)
      {
         Mat3[i][j] += Mat1[i][k] * Mat2[k][j];
      }
   }
}

【讨论】:

  • @PaulMcKenzie 如果我希望用户在输入的数字不匹配时再试一次怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
相关资源
最近更新 更多