简体   繁体   English

错误的数组值

[英]wrong array values

I have 2D array but if I change x coordinate, everytime I get wrong result.我有二维数组,但如果我改变 x 坐标,每次我都会得到错误的结果。

  int[][] arr = {{0, 2, 0, 0, 1},{0, 2, 0, 0, 1},{0, 2, 0, 0, 1},{0, 2, 0, 0, 1},{0, 2, 0, 0, 1}};
int now, previous;

   for (int i = 1; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        now = arr[i][j];
        previous = arr[i-1][j];
        }
   }

The result of variable now is 0, 2, 0, 0, 1... Why I want to have only 2, 0, 0, 1 If I change i coordinate of variable for Example i = 1 the output is still 0, 2, 0, 0, 1... Do you know where is problem?变量的结果现在是 0, 2, 0, 0, 1... 为什么我只想有 2, 0, 0, 1 如果我更改变量的 i 坐标,例如 i = 1 output 仍然是 0, 2 , 0, 0, 1 ... 你知道问题在哪里吗? Thanks谢谢

You need to put j = 1 instead of j = 0.您需要将 j = 1 而不是 j = 0。

The i variable is iterating over the vectors that compose your array, while the j variable is iterating over each element of one of those vectors. i 变量遍历构成数组的向量,而 j 变量遍历其中一个向量的每个元素。 You want to skip the first element of each vector, so you should change j to start at 1 instead of 0.您想要跳过每个向量的第一个元素,因此您应该将 j 更改为从 1 而不是 0 开始。

In any case, you are repeating the attribution inside a loop, and only the last value assigned to the variables will be kept.在任何情况下,您都在循环内重复属性,并且只会保留分配给变量的最后一个值。 So assuming this is the original code you're using, you should remove the "for" loops and do the attributions directly, assuming your arr array will not change.因此,假设这是您正在使用的原始代码,您应该删除“for”循环并直接进行归因,假设您的 arr 数组不会改变。

because i corresponds to the outer array in your example.因为 i 对应于您示例中的外部数组。 what you have will print 0, 2, 0, 0, 1 four times.你所拥有的将打印0, 2, 0, 0, 1四次。 I gather what you want is to show 2, 0, 0, 1 five times... for that you should be doing我知道你想要的是显示2, 0, 0, 1五次......你应该这样做

for (int i = 0; i < 5; i++) {
 for (int j = 1; j < 5; j++) {
     now = arr[i][j];
     previous = arr[i-1][j];
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM