首页 > 解决方案 > 我在这里做错了什么?为什么代码没有给出所需的输出?

问题描述

我正在尝试为矩阵乘法编写代码。我不知道我在这段代码中做错了什么,因为编译器没有给出错误,但程序仍然无法运行。我附上了输出的照片,代码在 2x2 矩阵中运行良好,但除此之外它不能正常工作。

#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[20][20], b[20][20], mul[20][20];
int m1, n1, m2, n2;
int i1, j1, i2, j2, i3, j3, k;
int sum = 0;
printf("Enter the number of Rows and Column for Matrix A: ");
scanf("%d %d", &m1, &n1);
printf("Enter the number of Rows and Column for Matrix B: ");
scanf("%d %d", &m2, &n2);

if (n1 == m2)
{
    printf("Insert elements in matrix A-\n");
    
    for (i1 = 1; i1 <= n1; i1++)
    {
        for (int j1 = 1; j1 <= m1; j1++)
        {
            printf("Enter A[%d][%d]: ", i1, j1);
            scanf("%d", &a[i1][j1]);
        }
    }
    
    printf("\n");
    
    printf("Insert elements in matrix B-\n");
    
    for (i2 = 1; i2 <= n2; i2++)
    {
        for (j2 = 1; j2 <= m2; j2++)
        {
            printf("Enter B[%d][%d]: ", i2, j2);
            scanf("%d", &b[i2][j2]);
        }
    }

    printf("\n");

    printf("Matrix A-\n");
    
    for (int i = 1; i <= n1; i++)
    {
        for (int j = 1; j <= m1; j++)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

    printf("Matrix B-\n");
    
    for (int i = 1; i <= n2; i++)
    {
        for (int j = 1; j <= m2; j++)
        {
            printf("%d ", b[i][j]);
        }
        printf("\n");
    }

    for (i3 = 1; i3 <= m1; i3++)
    {
        for (j3 = 1; j3 <= n2; j3++)
        {
            for (k = 1; k <= m2; k++)
            {
                sum = sum + a[i3][k] * b[k][j3];
            }
            mul[i3][j3] = sum;
            sum = 0;
        }
    }

    printf("\nThe Multiplication Matrix of the two entered Matrices is:\n");
    
    for (int i = 1; i <= m1; i++)
    {
        for (int j = 1; j <= n2; j++)
        {
            printf("%d ", mul[i][j]);
        }
        printf("\n");
    }
}
else
{
    printf("The given information is not valid.\nFor the multiplication of two matrices (AxB), the no. of Columns of A should be equal to the no. of Rows of B.\nCheck the given Data.\n");
    printf("Your given Data:-\nRow & Column of A = %d, %d\nRow & Column of B = %d, %d\n", m1, n1, m2, n2);
}
return 0;
}

对于 2x2 矩阵

对于 2X3 和 3x2 矩阵

对于 1x3 和 3x4 矩阵

标签: cmatrixerror-handlingmatrix-multiplication

解决方案


推荐阅读