简体   繁体   中英

How to calculate matrix multiplication in language C

I tried this code but something is wrong

        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");
    }

when i debug it it prints out random numbers in both rows and columns (something like -895473 )

Missing braces.

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
}

The braces on the inside aren't strictly necessary but if you always use braces you are less likely to make this particular mistake in the future.

Without the braces, it looks like this, correctly indented:

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;             
}

This is more obviously wrong. Another way to make the error less likely is to move the variables inside the loops:

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;             
    }
}

This way, if you remove the braces, you will get an error because j is not defined. (This doesn't work in C90, but that's ancient history these days.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM