矩阵乘法函数C ++ [英] Matrix multiplication function C++

查看:484
本文介绍了矩阵乘法函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎对我的矩阵乘法函数有一个问题。

I seem to have an issue with my matrix multiplication function.

当我运行程序,我只是得到一个nxn矩阵,所有的值相同,一些有线双值,例如21312e-2
这是我的功能代码:

When I run the program I just get an n x n matrix with all of the values the same, as some wired double value, e.g 21312e-2 Here is my function code:

void Multiply(int i, int j, double mat1[10][10], double mat2[10][10]) {


double mat3[10][10];
for (int r = 0; r < i; r++) {
    for (int c = 0; c < j; c++) {
        for (int in = 0; in < i; in++) {
            mat3[r][c] += mat1[r][in] * mat2[in][c];
        }
        cout << mat3[r][c] << "  ";
    }
    cout << "\n";
}

}

使用以下函数将mat1和mat 2读入主线程中的程序:

mat1 and mat 2 are read into the program in the main thread using the function read:

void read_matrix(int m, int n, double mat[10][10])
{
    int i, j;
    for (i = 0; i<m; ++i)
        for (j = 0; j<n; ++j)
            cin >> mat[i][j];
}

编辑:主代码

int main()
{
    int i1, i2, j1, j2;
    double mat1[10][10], mat2[10][10], mat3[10][10];

    scanf_s("%d %d\n", &i1, &j1, mat1);


    read_matrix(i1, j1, mat1);

    scanf_s("%d %d\n", &i2, &j2, mat2);

    read_matrix(i2, j2, mat2);

    printf("%d x %d matrix\n", i1, j1);
    print_matrix(i1, j1, mat1);
    printf("\n%d x %d matrix\n", i2, j2);
    print_matrix(i2, j2, mat2);

    Multiply(i1, j2, mat1, mat2);
    system("pause");
    return 0;
}


推荐答案

c $ c> mat3 ,在添加之前为零值。

You need to fill mat3 with a zero value before adding to it.

最简单的方法是使用:

double mat3[10][10] = {};

这篇关于矩阵乘法函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆