开发者

Multiplying two 3x3 matrices in C

I am trying to multiply two 3x3 matrices. The first 2 numbers in the first and second row are the only correct answer. What am I doing wro开发者_C百科ng? Is the stuff I need declared in mult_matrices?

#include <stdio.h>

void mult_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);

int main()
{
    int p[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}};
    int q[3][3] = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
    int r[3][3];

    mult_matrices(p, q, r);
    print_matrix(r);
}

void mult_matrices(int a[][3], int b[][3], int result[][3])
{
    int i, j, k;
    for(i = 0; i < 3; i++)
    {
            for(j = 0; j < 3; j++)
            {
                    for(k = 0; k < 3; k++)
                    {
                            result[i][j] +=  a[i][k] *  b[k][j];
                    }
            }
    }
}

void print_matrix(int a[][3])
{
    int i, j;
    for (i = 0; i < 3; i++)
    {
            for(j = 0; j < 3; j++)
            {
                    printf("%d\t", a[i][j]);
            }
            printf("\n");
    }
 }


Make sure you initialize r to all zeros before you use it.

int r[3][3] = { 0 };


Looks like you're not initializing your result matrix.

i.e. Change:

int r[3][3];

to

int r[3][3] ={{0,0,0},{0,0,0},{0,0,0}};


One thing that I notice that you don't do is initialize you're r[3][3] array. I am not sure if this is the root of you're problem but it very well could be. Essentially what the values of r are set to is whatever was "left over" in memory in that location. Sometimes they will all be 0 but most likely they will not be. So it could be the issue you are having, but even if it isn't it is good to always get in a habit of initializing all of you're variables.


int main(){ 
  int A[3][3],B[3][3],C[3][3],i,j; 
  printf("Please Enter 9 Numbers for First Matrix") 
  for(i=0;i<=2;i++){
    for(j=0;j<=2;j++){ 
      scanf("%d",A[i][j]);
    }
  }
  printf("Please Enter 9 Numbers for Second Matrix") 
  for(i=0;i<=2;i++){ 
    for(j=0;j<=2;j++){ 
      scanf("%d",B[i][j]); 
    }
  } 
  for(i=0;i<=2;i++){ 
    for(j=0;j<=2;j++){ 
      C[i][j]=A[i][j]+B[i][j] 
      printf("%d "C[i][j]); 
    } 
    printf("\n");
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜