C中矩阵乘法的结果不正确

时间:2013-03-20 00:13:40

标签: c arrays matrix-multiplication

我正在学习使用顺序存储器来表示矩阵。我做了以下程序,但结果不正确。有人能告诉我哪里出错了。我正在粘贴我正在使用顺序存储器的程序和我没有使用过的程序并且是正确的。我在顺序存储器中得到的结果不正确。

#include <stdio.h>
#include <stdlib.h>
 int main() 
 {
    int i, m, n, p, q, c, d, k, sum = 0;
    int *first, *second, *multiply;
    printf("Enter the number of rows and columns of first matrix\n");
    scanf("%d%d", &m, &n);
    printf("Value entered %d%d \n",m,n);
    first = malloc(m*n*sizeof(int*));
    printf("Enter the number of rows and columns of second matrix \n");
    scanf("%d%d", &p,&q); 
    printf("value entered %d%d \n",p,q); 
    second = malloc(p*q*sizeof(int));
    multiply = malloc(m*n*sizeof(int));
    printf("Enter the elements of first matrix\n");
    for( c = 0 ; c < m ; c++ )
       for ( d = 0 ; d < n ; d++ )
         scanf("%d", &first[c*m+d]);
      if ( n != p )
     printf("Matrices with entered orders can't be multiplied with each other.\n");
     else {
      printf("Enter the elements of second matrix\n");
     for ( c = 0 ; c < p ; c++ ){
        for ( d = 0 ; d < q ; d++ )
        scanf("%d", &second[c*p+d]);
   }

 for ( c = 0 ; c < m ; c++ ) {
  for ( d = 0 ; d < q ; d++ ) {
    for ( k = 0 ; k < p ; k++ ) {
      sum = sum + first[c*m+k]*second[k*p+d];
    }
    multiply[c*m+d] = sum;
    sum = 0;
    }

  }

     printf("Product of entered matrices:-\n");
     for ( c = 0 ; c < m ; c++ ) {
       for ( d = 0 ; d < q ; d++ )
    printf("%d\t", multiply[c*m+d]);
  printf("\n");
   }

    free(second);

   free(multiply);
} 

  free(first);
   return 0;
}

2 个答案:

答案 0 :(得分:3)

sum = sum + first[c*m+k]*second[k*p+d];

必须是

sum = sum + first[c*n+k]*second[k*q+d];

由于first行的长度为nsecond行的长度为q

答案 1 :(得分:0)

for( c = 0 ; c < m ; c++ )
   for ( d = 0 ; d < n ; d++ )
     scanf("%d", &first[c*m+d]); // error
                          ^ n    // fix

多次出现同样的错误