[英]Multiplying two 3x3 matrices in C
I am trying to multiply two 3x3 matrices. 我试图将两个3x3矩阵相乘。 The first 2 numbers in the first and second row are the only correct answer.
第一行和第二行中的前两个数字是唯一正确的答案。 What am I doing wrong?
我究竟做错了什么? Is the stuff I need declared in
mult_matrices
? 我需要在
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");
}
}
确保在使用之前将r
初始化为全零。
int r[3][3] = { 0 };
Looks like you're not initializing your result
matrix. 看起来您没有初始化
result
矩阵。
ie 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. 我注意到你没有做的一件事是初始化你的r [3] [3]数组。 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.
基本上r的值被设置为在该位置的内存中“遗留”的内容。 Sometimes they will all be 0 but most likely they will not be.
有时它们都会为0但很可能不是。 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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.