-2

我正在学习将顺序内存用于矩阵。我制作了以下程序,但结果不正确。有人可以告诉我哪里出错了。我正在粘贴我正在使用顺序内存的两个程序和一个我没有使用并且是正确的程序。我在顺序一个中得到不正确的结果。

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

2 回答 2

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

一定是

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

因为 的 行的长度firstn, 的 行的长度secondq

于 2013-03-20T00:17:29.953 回答
0
for( c = 0 ; c < m ; c++ )
   for ( d = 0 ; d < n ; d++ )
     scanf("%d", &first[c*m+d]); // error
                          ^ n    // fix

多次出现同样的错误

于 2013-03-20T00:18:12.693 回答