本文介绍了为什么我+ = i + a [i ++] + a [i ++] + a [i ++]结果为8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全迷失了获得这些结果的原因:

I am totally lost why I get these results:

    int i = 1;

    int[] a = new int[6];
    a[0] = 0;
    a[1] = 1;
    a[2] = 2;
    a[3] = 3;
    a[4] = 4;
    a[5] = 5;

    i += i + a[i++] + a[i++];
   //i is 5

   i = 1;

   i += i + a[i++] + a[i++] + a[i++];
   // i is 8

我(错误地)认为有以下选择:

I (wrongly) thought that there are these options:

  1. i = i(=1) + a[i++] +等-表示缓存了i = 1,而不缓存然后改变了.表达式评估顺序从左到右是的,我猜(?!).
  2. i增加,导致(对于第一个示例)在i = i(=3) + a[1] + a[2]中现在i = 3并写入最左边的i
  3. 最右边的a [THIS_VALUE]中的
  4. 值将替换为最左边的i,并且永远不会进行最后一个增量.
  1. i = i(=1) + a[i++] + etc - meaning that i = 1 is cached and notchanged then. Expression evaluation order is exactly from left toright, I guess (?!).
  2. i is increased, which results (for first example) in i = i(=3) + a[1] + a[2] now i = 3 and written to leftmost i
  3. value from rightmost a[THIS_VALUE] is substituted into leftmost i, and last increment is never made.

但是实际结果让我毫无头绪...

But actual results leave me with no clue...

推荐答案

i += i + a[i++] + a[i++];

将i的原始值添加到表达式i + a[i++] + a[i++]的值中,并将结果分配给i.

adds the original value of i to the value of the expression i + a[i++] + a[i++] and assigns the result to i.

等效于

i = i + i + a[i++] + a[i++];
    1 + 1 + a[1]   + a[2]    = 1 + 1 + 1 + 2 = 5

然后您将1分配给i并计算:

Then you assign 1 to i and calculate:

i += i + a[i++] + a[i++] + a[i++];

等效于

i = i + i + a[i++] + a[i++] + a[i++];
    1 + 1 + a[1]   + a[2]   + a[3] = 1 + 1 + 1 + 2 + 3 = 8

要注意的重要一点是,每个a[i++]都将i递增,但是在i的上一个值(即递增之前的值)的索引处访问a的元素.

The important thing to note is that each a[i++] increments i, but accesses the element of a at the index of the previous value of i (i.e. the value prior to the increment).

因此第一个a[i++]返回a[1](即使i递增到2),第二个a[i++]返回a[2](即使i递增到3),第三个a[i++]返回a[3](即使i递增到4).

Therefore the first a[i++] returns a[1] (even though i is incremented to 2), the second a[i++] returns a[2] (even though i is incremented to 3) and the third a[i++] returns a[3] (even though i is incremented to 4).

这篇关于为什么我+ = i + a [i ++] + a [i ++] + a [i ++]结果为8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:20