加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中乘以两个矩阵

发布时间:2020-12-16 09:53:46 所属栏目:百科 来源:网络整理
导读:我正在编写一个程序,它接受两个不同矩阵的元素,然后它将它们相乘,接下来它将它们保存在一个多维数组中. 但它只适用于方阵. (Visual Studio 2013没有错误.) 如果你帮我编辑这段代码以便繁殖各种矩阵,我会很高兴的. int a,b,c,d; int Mat1[10][10]; int Mat2[1
我正在编写一个程序,它接受两个不同矩阵的元素,然后它将它们相乘,接下来它将它们保存在一个多维数组中.
但它只适用于方阵. (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 ) nnEnter 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 ) nnEnter 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 (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];
      }
   }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读