我正在做一个将两个可变大小的二维矩阵相乘的作业。
我一直遇到同样的问题,并且一直在思考如何解决它:当调用输入来定义矩阵时,该行的最后一列由于某种原因没有得到输入。相反,下一行的第一列被写入两个位置。
例如,如果您尝试输入 2 x 2
1 2
3 4
它将被存储为
1 3
3 4
我四处搜索,似乎找不到任何类似的问题。它对任何大小都做同样的事情,所有输入都很好,直到行的最后一个位置。如果它是最后一行,最后一个位置保持良好。
我将在此处发布代码,如果有人可以给我任何指示以指出解决此问题的方向,我将不胜感激。 (以及关于清理其余部分的任何指示,它的功能,但我确信它对有经验的人来说并不漂亮。)
我相信罪魁祸首就在这里
for(j=0; j < Rows_1; ++j){
for(i=0; i < Columns_1; ++i){
printf("\nEnter the value for row %d column %d=",j+1,i+1);
/*fgets(input, sizeof(input)-1, stdin);
sscanf("%d", &Matrix_1[j][i]);*/
scanf("%d",&Matrix_1[j][i]);
}
}
全部代码在这里
//HW5....Program for Matrix Multiplication....
int main(void){
//first we will verify that the two matrices can be mulitiplied by comparing rows and columns....
static int Rows_1, Columns_1, Rows_2, Columns_2;
int i, j, k, l, m, n, p, q;
//char input[4];
//call for user input to define size of matrix 1 and matrix 2
printf("Please enter the size of the first matrix you wish to multiply...\n# of Rows=");
scanf("%d",&Rows_1);
printf("# of Columns=");
scanf("%d",&Columns_1);
printf("Please enter the size the second matrix you wish to multiply...\n# of Rows=");
scanf("%d",&Rows_2);
printf("# of Columns=");
scanf("%d",&Columns_2);
//defining the size of the matrices using inputted values (-1 because arrays count 0 as a row.)
int Matrix_1[(Rows_1-1)][(Columns_1-1)],Matrix_2[(Rows_2-1)][(Columns_2-1)];
if(Rows_2==Columns_1){ //checking if the two matrices are compatible in size to be multiplied
printf("\nYou are attempting to multiply a %d x %d matrix with a %d x %d matrix",Rows_1, Columns_1, Rows_2, Columns_2);
printf("\nThe resulting matrix will be %d x %d",Rows_1, Columns_2);
for(j=0; j < Rows_1; ++j){
for(i=0; i < Columns_1; ++i){
printf("\nEnter the value for row %d column %d=",j+1,i+1);
/*fgets(input, sizeof(input)-1, stdin);
sscanf("%d", &Matrix_1[j][i]);*/
scanf("%d",&Matrix_1[j][i]);
}
}
//printf("%d %d %d %d",Matrix_1[0][0],Matrix_1[0][1],Matrix_1[1][0],Matrix_1[1][1]);
/* for(k=0; k < Rows_2; k++){
for(l=0; l < Columns_2; l++){
printf("Enter the value for row %d column %d",k+1,l+1);
scanf("%d",&Matrix_2[k][l]);
}
}*/
printf("Matrix 1 =\n");
for(p=0; p < Rows_1; ++p){
for(q=0; q < Columns_1; ++q){
printf("%d ",Matrix_1[p][q]);
}
printf("\n");
}
/* printf("Matrix 2 =/n");
for(m=0; m < Rows_2; m++){
for(n=0; n < Columns_2; n++){
printf("%d ",Matrix_2[m][n]);
}
printf("\n");
}
*/
}
else{
printf("\nThe two matrices entered cannot be multiplied together.");
}
;
getchar();
return 0;
}
感谢您的关注!
最佳答案
你的问题在这里:
//defining the size of the matrices using inputted values (-1 because arrays count 0 as a row.)
int Matrix_1[(Rows_1-1)][(Columns_1-1)],Matrix_2[(Rows_2-1)][(Columns_2-1)];
你不应该使用“-1”。尽管数组从 0 开始计数,并且它们以“n-1”结束,但它们必须声明为“n”大小:
int Matrix_1[Rows_1][Columns_1],Matrix_2[Rows_2][Columns_2];
关于c - 输入写入 C 中数组的错误位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836053/