Программа C для умножения прямоугольных матриц с использованием массивов не печатает результирующую матрицу

Я приложил все усилия, чтобы написать программу на языке C для умножения прямоугольных матриц, но при компиляции и запуске программы результирующая матрица не печатается вместе с произведениями. В качестве пользовательского ввода я попробовал ввести 2 строки и 3 столбца для матрицы A и 3 строки и 2 столбца для матрицы B.

Как я могу исправить приведенный ниже код?

#include<stdio.h>
int main()
{
    int i,j,r,c,r1,c1,r2,c2,k,a[10][10],b[10][10],result[10][10];
    printf("\n Enter the no. of rows and column desired for the 1st matrix (between 1 to 10):");
    scanf("%d%d",&r1,&c1);
    printf("\n Enter the no. of rows and columns for the 2nd matrix - between 1 to 10 (Pls note that no. of rows of 1st matrix should be equal to the no. of columns in the 2nd matrix for multiplication):");
    scanf("%d%d",&r2,&c2);
    
    printf("\n Enter the elements of the 1st Matrix:");
    for(i=0;i<r1;i++){
        for(j=0;j<c1;j++){
            scanf("%d",&a[i][j]);
        }
    }
    
    printf("\n Print of 1st Matrix:\n");
    for(i=0;i<r1;i++){
        for(j=0;j<c1;j++){
            printf("\t%d",a[i][j]);
        }
        printf("\n");
    }
    
    printf("\n Enter the elements of the 2nd Matrix:");
    for(i=0;i<r2;i++){
        for(j=0;j<c2;j++){
            scanf("%d",&b[i][j]);
        }
    }
    
    printf("\n Print of 2nd Matrix:\n");
    for(i=0;i<r2;i++){
        for(j=0;j<c2;j++){
            printf("\t%d",b[i][j]);
        }
        printf("\n");
    }
    
    //multiplying 1st and 2nd matrices and storing the results in results[i][j]
    for(i=0;i<r1;i++){
        for(j=0;j<c2;j++){
            for(k=0;k<c1;k++){
                result[i][j] = result[i][j] + (a[i][k] * b[k][j]);
            }
        }
    }
    
    //Printing the results
    printf("\n After Multiplication of two matrices:\n");
    for(i=0;i<r;i++){
        for(j=0;j<c;j++){
            printf("\t%d",result[i][j]);
        }
        printf("\n");
    }
    return 0;
}

🤔 А знаете ли вы, что...
C оставался популярным и актуальным языком программирования на протяжении многих десятилетий.


68
1

Ответ:

Решено

В вашем коде есть некоторые проблемы.

Инициализация матрицы результатов

Я предлагаю вам изменить код таким образом

//multiplying 1st and 2nd matrices and storing the results in results[i][j]
       for(i=0;i<r1;i++){
        for(j=0;j<c2;j++){

            //init i,j element of result matrix

            result[i][j] = 0;   //add here the initialisation
            for(k=0;k<c1;k++){
                
                result[i][j] = result[i][j] + (a[i][k] * b[k][j]);
            }
        }
    }

Цикл вывода на печать

В своем коде вы использовали переменные r и c без их инициализации. это основная причина неправильного вывода. Измените код следующим образом:

for(i=0;i<r1;i++){
        for(j=0;j<c2;j++){
            printf("\t%d",result[i][j]);
        }
        printf("\n");
    }

Новый код

Здесь приведен готовый код вашей программы с исправлениями и некоторыми улучшениями в операторах scanf.

#include<stdio.h>
int main()
{
    int i,j,r1,c1,r2,c2,k,a[10][10],b[10][10];
    int result[10][10];
    printf("\n Enter the no. of rows and column desired for the 1st matrix (between 1 to 10):");
    scanf("%d %d",&r1,&c1);   //put a space between escape codes in order to avoid conversion issues
    printf("\n Enter the no. of rows and columns for the 2nd matrix - between 1 to 10 (Pls note that no. of rows of 1st matrix should be equal to the no. of columns in the 2nd matrix for multiplication):");
    scanf("%d %d",&r2,&c2);   //put a space between escape codes in order to avoid conversion issues
    
    printf("\n Enter the elements of the 1st Matrix:");
    for(i=0;i<r1;i++){
        for(j=0;j<c1;j++){
            scanf("%d",&a[i][j]);
        }
    }
    
    printf("\n Print of 1st Matrix:\n");
    for(i=0;i<r1;i++){
        for(j=0;j<c1;j++){
            printf("\t%d",a[i][j]);
        }
        printf("\n");
    }
    
    printf("\n Enter the elements of the 2nd Matrix:");
    for(i=0;i<r2;i++){
        for(j=0;j<c2;j++){
            scanf("%d",&b[i][j]);
        }
    }
    

    printf("\n Print of 2nd Matrix:\n");
    for(i=0;i<r2;i++){
        for(j=0;j<c2;j++){
            printf("\t%d",b[i][j]);
        }
        printf("\n");
    }
    
    //multiplying 1st and 2nd matrices and storing the results in results[i][j]
       for(i=0;i<r1;i++){
        for(j=0;j<c2;j++){
            //init i,j element of result matrix
            result[i][j] = 0.0;
            for(k=0;k<c1;k++){
                printf("(%d %d %d) %f - %d - %d\n",i,j,k,result[i][j],a[i][k],b[k][j]);
                result[i][j] = result[i][j] + (a[i][k] * b[k][j]);
            }
        }
    }
    
    //Printing the results
    printf("\n After Multiplication of two matrices:\n");
    for(i=0;i<r1;i++){
        for(j=0;j<c2;j++){
            printf("\t%d",result[i][j]);
        }
        printf("\n");
    }
    return 0;
}