编译两个矩阵相加的代码后,我显示了意外的值,以 63.. 开头,长度为七位数字。我还初始化了结果矩阵(它是前两个矩阵的总和)。
#include<stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,m1,m2,n1,n2;
printf("Enter the order of the matrix a: ");
scanf("%d%d",&m1,&n1);
printf("Enter the order of the matrix b: ");
scanf("%d%d",&m2,&n2);
if(m1==m2&&n1==n2)
{
//input of the elements to the matrix 'a'
printf("Enter the elements of the matrix a: ");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
scanf("%d",&a[i][j]);
}
}
//input of the elements to the matrix 'b'
printf("Enter the elements of the matrix b: ");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
scanf("%d",&b[i][j]);
}
//initialization of the matrix 'c'
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
c[i][j]=0;
}
//adding the matrices 'a' and 'b'
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d ",&c[i][j]);
}
printf("\n");
}
else
printf("The matrices cannot be added");
}
最佳答案
首先,if-else
的构造不正确。之前的 }
//input of the elements to the matrix 'b'
标记 if 子句的结束,这当然不是您想要的。
除此之外,
printf("%d ",&c[i][j]);
应该是
printf("%d ",c[i][j]); // You don't need & while printing.
<小时/>
作为旁注,
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
c[i][j]=0;
}
是可以避免的,您不能将c[i][j]
初始化为零。
如果您必须将 c
的每个元素初始化为零,那么您可以这样做
int c[4][4]={0}; // partial-initilization forces rest of the elements to be zero
该标准在 ISO/IEC 中表示 9899:201x->6.79->21
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
最后一点可以用6.79->10来理解
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
关于c - 我的 C 程序中两个矩阵相加的输出显示意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38974403/