使用以下代码我无法打印任何矩阵A,B或C.
作为测试目的,甚至不打印int。
#include"stdio.h"
int main()
{
#define row 3
#define col 3
int A[row][col]={ {1,2,3},{2,3,4},{3,4,5}};
int B[row][col]={ {1,0,0},{0,1,0},{0,0,1}};
int i,j;
int C[row][col]={ {0,0,0},{0,0,0},{0,0,0}};
int temp=2;
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=A[i][j]*B[j][i]+C[i][j];
}
printf("%d \n ", C[i][j]);
getchar();
}
}
答案 0 :(得分:3)
您的代码中存在问题:
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=A[i][j]*B[j][i]+C[i][j];
}
// j contains 3 here therefore you acess the C array out of bounds
printf("%d \n ", C[i][j]); //<<<<<<<<<<<<<<
getchar();
}
你可能想要这个:
...
// Multiplication of A and B
for (i = 0; i<3; i++)
{
for (j = 0; j<3; j++)
{
C[i][j] = A[i][j] * B[j][i] + C[i][j];
}
}
// Display C
for (i = 0; i<3; i++)
{
for (j = 0; j<3; j++)
{
printf ("%d ", C[i][j]);
}
printf("\n");
}
getchar();
...
更好:编写Display3x3Matrix并使用它:
void Display3x3Matrix(int m[3][3])
{
for (int i = 0; i<3; i++)
{
for (int j = 0; j<3; j++)
{
printf("%d ", m[i][j]);
}
printf("\n");
}
}
...
printf("A\n");
Display3x3Matrix(A);
printf("\nB\n");
Display3x3Matrix(B);
printf("\nC\n");
Display3x3Matrix(C);
答案 1 :(得分:1)
这对我有用(打印&#34; A&#34; Matrix):
#define row 3
#define col 3
int A[row][col] = { { 1,2,3 },{ 2,3,4 },{ 3,4,5 } };
int rows, columns;
for (rows = 0; rows<3; rows++)
{
for (int columns = 0; columns<3; columns++)
{
printf("%d ", A[rows][columns]);
}
printf("\n");
}
答案 2 :(得分:0)
按如下所示更改for循环
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=A[i][j]*B[j][i]+C[i][j];
printf("%d", C[i][j]);
}
printf("\n");
}