如何用C语言计算矩阵乘法

时间:2016-04-20 22:11:40

标签: c matrix-multiplication

我尝试了这段代码,但出了点问题

        for (i = 0; i < row1; i++) {
        for (j = 0; j < col2; j++)
            suma = 0;
            for (l = 0; l < row2; l++)
            suma += a[i][l] * bt[l][j];
            c[i][j] = suma;             
    }
    printf("\nMultiplication of 2 matrices:\n");
    for (i = 0; i < row1; i++) {
        for (j = 0; j < col2; j++)
            printf("%2d", c[i][j]);
        printf("\n");
    }

当我调试它时,它会在行和列中打印出随机数(类似于-895473)

1 个答案:

答案 0 :(得分:5)

缺少牙箍。

for (i = 0; i < row1; i++) {
    for (j = 0; j < col2; j++) { // added brace
        suma = 0;
        for (l = 0; l < row2; l++) { // added brace
            suma += a[i][l] * bt[l][j];
        } // added brace
        c[i][j] = suma;             
    } // added brace
}

内部的大括号不是严格必要但是如果你总是使用大括号,你将来不太可能犯这个特别的错误。

没有大括号,它看起来像这样,正确缩进:

for (i = 0; i < row1; i++) {
    for (j = 0; j < col2; j++)
        suma = 0;
    // Note that j = col2, which means that we are accessing
    // array elements out of bounds, which is an error.
    for (l = 0; l < row2; l++)
        suma += a[i][l] * bt[l][j];
    c[i][j] = suma;             
}

这显然是错误的。另一种使错误不太可能的方法是在循环中移动变量:

for (int i = 0; i < row1; i++) {
    for (int j = 0; j < col2; j++) {
        double suma = 0;
        for (int l = 0; l < row2; l++) {
            suma += a[i][l] * bt[l][j];
        }
        c[i][j] = suma;             
    }
}

这样,如果删除大括号,则会收到错误,因为未定义j。 (这在C90中不起作用,但现在这是古老的历史。)