簡體   English   中英

矩陣乘法

[英]Matrix multiplication

我不明白哪里出了錯。 請幫我改正。 由於結果矩陣的所有元素均為零,因此輸出即將到來。

 #include<stdio.h>
#include<conio.h>
int main()
{
    int a[5][5],b[5][5],c[5][5],i=0,j=0,row1,col1,row2,col2,row3,col3,s=0,k=0,l=0;
    printf("Enter no. of rows and no. of columns of first matrix:\n");
    scanf("%d %d",&row1,&col1);
    printf("Enter no. of rows and no. of columns of second matrix:\n");
    scanf("%d %d",&row2,&col2);
    if(col1==row2)
    {
                  row3=row1;
                  col3=col2;
    }
    else
    {
        printf("Not possible!");
        exit(1);
    }

    printf("Enter elements of first matrix:\n");
    for(i=0;i<row1;i++)
    {
                       for(j=0;j<col1;j++)
                       {
                                          scanf("%d",&a[i][j]);
                       }
    }


        printf("Enter elements of second matrix:\n");
    for(i=0;i<row2;i++)
    {
                       for(j=0;j<col2;j++)
                       {
                                          scanf("%d",&b[i][j]);
                       }
    }

    i=0;
    j=0;

    for(k=0;k<row3;k++)
    {
                       for(l=0;l<col3;l++)
                       {

                                          while(i<row3 || j<col3)
                                          {
                                                       //printf("Hi");
                                                       s=s+a[i][j++]*b[i++][j];
                                                       //printf("%d\n",s);

                                          }

                       }
                       printf("%d\n",s);
                       c[k][l]=s;
                        s=0;
    }


    printf("Sum matrix is:\n");
        for(k=0;k<row3;k++)
    {
                       for(l=0;l<col3;l++)
                       {
                                          printf("%d ",c[k][l]);
                       }
                       printf("\n");
    }
    getch();
}

我在while循環中包含了打印注釋,以便進行調試,但無濟於事。

您正在列循環之外設置結果,因此每行只設置一個結果。 通過在大括號內移動這3行,將代碼更改為此:

for(k=0;k<row3;k++)
{
      for(l=0;l<col3;l++)
      {
          i = 0; j = 0;
          while(i<row3 || j<col3)
          {
              //printf("Hi");
              s=s+a[k][j++]*b[i++][l];
              //printf("%d\n",s);
           }

           // THIS CODE HAS MOVED:
           printf("%d\n",s);
           c[k][l]=s;
           s=0;
     }
}

另外,您的加法需要使用k和l索引,以便沿着k給定的a [] []行和l給定的b [] []列移動:

s=s+a[k][j++]*b[i++][l];

您忘記在將兩個矩陣相加的循環內初始化i和j。

根據您的代碼添加。

i = 0; 在用於加法的double for循環內j = 0。

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM