2013-03-20 2 views
-2

J'apprends à utiliser la mémoire séquentielle pour les matrices. J'ai fait le programme suivant mais il donne un résultat incorrect. Quelqu'un peut-il me dire où je me suis trompé? Je colle les deux programmes où j'utilise la mémoire séquentielle et un dans lequel je n'ai pas utilisé et est correct. J'obtiens des résultats incorrects en séquentiel.Résultat incorrect dans la multiplication de la matrice en C

#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; 
} 
+0

Avez-vous essayé vérifier des erreurs, avez-vous essayé le déboguer? –

+0

Je vais supprimer mon downvote si vous corrigez l'indentation. – kay

+5

"Hé, regarde, un mur de code, fixe le Stack Overflow!" <- pas comment ce site est destiné à fonctionner. –

Répondre

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

doit être

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

puisque la longueur des rangées de first est n, et la longueur des rangées de second est q.

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

La même erreur plusieurs fois

Questions connexes