I am trying to understand this code from the book.
我试图从书中理解这段代码。
int[][] grade = {
{ 1, 0, 1 },
{ 0, 1, 0 },
{ 1, 0, 1 }
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j)
System.out.print(grade[i][j] + grade[j][i] + " ");
else
System.out.print(grade[i][j] * grade[j][i] + " ");
}
System.out.println(" ");
}
I understand the logic of a two-dimensional arrays being rows and columns. I just don’t understand how the answer came to be this.
我理解二维数组的逻辑是行和列。我只是不明白答案是怎么回事。
2 0 1
0 2 0
1 0 2
2 个解决方案
#1
0
It loops through the 2 dimensional array. If i is equal to j, e.g ( 0,0 1,1 2,2 ) then it adds grade[i][j] with grade[j][i]. Since i and j are equal it adds the location with itself.
它循环通过二维数组。如果i等于j,例如(0,0 1,1 2,2),则它将等级[i] [j]与等级[j] [i]相加。由于i和j相等,它会自己添加位置。
When i is not equal to j it multiplies grade[i][j] with grade[j][i].
当i不等于j时,它将grade [i] [j]与等级[j] [i]相乘。
Since they are not equal it multiplies 2 different positions in the grid. e.g.
由于它们不相等,它在网格中乘以2个不同的位置。例如
grade [3][1] is multiplied by grade[1][3], not by itself.
等级[3] [1]乘以等级[1] [3],而不是它自己。
If you changed grade[1][3] to 2, then all corners would be output as 2
如果将等级[1] [3]更改为2,则所有角都将输出为2
The input:
1 0 2
0 1 0
1 0 1
would output:
2 0 2
0 2 0
2 0 2
#2
-1
It basically loops through the two dimensional array and if it sees that the column and row number (i and j) are the same it will add it with itself. i.e. times the diagonal by two. And for the rest of the entries it will multiply with itself.
它基本上循环遍历二维数组,如果它看到列和行号(i和j)相同,它将自己添加它。即将对角线乘以2。而对于其余的条目,它将与自身相乘。
#1
0
It loops through the 2 dimensional array. If i is equal to j, e.g ( 0,0 1,1 2,2 ) then it adds grade[i][j] with grade[j][i]. Since i and j are equal it adds the location with itself.
它循环通过二维数组。如果i等于j,例如(0,0 1,1 2,2),则它将等级[i] [j]与等级[j] [i]相加。由于i和j相等,它会自己添加位置。
When i is not equal to j it multiplies grade[i][j] with grade[j][i].
当i不等于j时,它将grade [i] [j]与等级[j] [i]相乘。
Since they are not equal it multiplies 2 different positions in the grid. e.g.
由于它们不相等,它在网格中乘以2个不同的位置。例如
grade [3][1] is multiplied by grade[1][3], not by itself.
等级[3] [1]乘以等级[1] [3],而不是它自己。
If you changed grade[1][3] to 2, then all corners would be output as 2
如果将等级[1] [3]更改为2,则所有角都将输出为2
The input:
1 0 2
0 1 0
1 0 1
would output:
2 0 2
0 2 0
2 0 2
#2
-1
It basically loops through the two dimensional array and if it sees that the column and row number (i and j) are the same it will add it with itself. i.e. times the diagonal by two. And for the rest of the entries it will multiply with itself.
它基本上循环遍历二维数组,如果它看到列和行号(i和j)相同,它将自己添加它。即将对角线乘以2。而对于其余的条目,它将与自身相乘。