我试图制作矩阵代数程序,所以我开始使用预先定义的3x3矩阵。对于未正确读入2D阵列的元素存在一些问题,因此我将其中一个分离出来。问题是连续的最后一个数字是作为下一行的第一个元素打印的。即阵列[1] [2]打印出阵列[2] [0]。
同样,如果我有一个3x3矩阵,我们从1到9,我想要第1行第3列(即3)的值,它会给我4.第2行也是如此3;值为6,但它给了我7.
我已经在打印声明中显示输入前的计数器值并且它们是正确的。我猜想有什么东西在扫描,但我真的很难过。任何帮助将不胜感激!
#include <stdio.h>
int matrix1[2][2];
void main(void)
{
int i = 0, j=0; //Row and column subscripts for the first matrix
//======================================================================================================//
//First Matrix
printf("This is for the first matrix");
for(i=0; i < 3; i++) //Start with row
{
for(j = 0; j < 3; j++)
{
printf("\nInsert the value at row %d, column %d: ", i+1,j+1); //+1 since array's begin at 0
printf("\ni is %d, j is %d", i,j); //Shows what elements the input will go into
scanf("%d", &matrix1[i][j]); //Enter value into row i column j
}
}
printf("\n\n%d", matrix1[1][2]); //test to see what's in the element
}
答案 0 :(得分:0)
#include <stdio.h>
#define ROWS 3
#define COLS 3
int matrix1[ROWS][COLS];
void main(void)
{
int i, j; //Row and column subscripts for the first matrix
//================================================================================
//First Matrix
printf("This is for the first matrix");
for(i=0; i < ROWS; i++) //Start with row
{
for(j = 0; j < COLS; j++)
{
printf("\nInsert the value at row %d, column %d: ", i+1,j+1);
printf("\ni is %d, j is %d", i,j);
scanf("%d", &matrix1[i][j]);
}
}
printf("\n\n%d", matrix1[1][2]); //test to see what's in the element
}
答案 1 :(得分:0)
我认为您对数组中数组索引号和元素总数感到困惑。
例如,当您有5个整数的数组时。
int ary[5] = {11,22,33,44,55};
`------------IN Memory-----------
| 11 || 22 || 33 | | 44 | | 55 |
------------------------------- `
0 1 2 3 4 <--------These are called Index numbers.
They always start with 0,Hence
they always end with(Total Number of elements - 1)
因此从上面的解释中你要么想要改变数组的大小
从int matrix[2][2]
到int matrix[3][3];
或强>
将for()
循环更改为
for(i=0; i < 2; i++) //changed i<3 to i<2
{
for(j = 0; j < 2; j++) //changed i<3 to i<2
{
// your Code.....
}
}