简体   繁体   English

c中手工执行,不明白index -1是什么意思

[英]Hand execution in c, don't understand what index -1 means

I have this code and I am trying to do a hand execution from it but I am not sure what index - 1 does.我有这段代码,我正在尝试从中手动执行,但我不确定index - 1是做什么的。 Should my result be 1,5,6,8,9 or 1,3,5,6,8 or am I completely wrong?我的结果应该是1,5,6,8,9还是1,3,5,6,8还是我完全错了?

void main() {
    int array[5] = {1,3,4,6,7};
    int index;

    for (index = 1; index < 5; index++) {
    array[index] = array[index - 1] + 2;
    }
}

values in array before start loop: 1,3,4,6,7开始循环前数组中的值:1,3,4,6,7

The value for index is set at the top of each iteration of the for loop. index 的值设置在 for 循环每次迭代的顶部。
So the first time through the loop, index is set to represent the value 1 .所以第一次通过循环时, index被设置为表示值1

  • so index-1 would hold the value 1-1 , or 0所以index-1将保存值1-1 ,或0
  • so array[index - 1] is the same as array[0]所以array[index - 1]array[0]相同
  • array[0] holds the value 1 . array[0]保存值1
  • hence array[index - 1] + 2 is the same as 1 + 2 , or 3因此array[index - 1] + 21 + 23
  • So then, we assign array[index] which we know to represent the array[1] which used to hold the value of 3 , now is assigned to (again) hold the value 3 .那么,我们分配array[index] ,我们知道它代表array[1] ,它曾经保存3的值,现在分配给(再次)保存值3

values in array at end of 1st time through the loop: 1,3,4,6,7第一次循环结束时数组中的值:1,3,4,6,7

Now, back up to the top of the loop.. index is told to increment itself by 1现在,回到循环的顶部.. index被告知将自身增加1
ie: index which was 1 , now represents the number 2即: index为 1 ,现在表示数字2

  • so index-1 would hold the value 2-1 , or 1 .所以index-1将保存值2-11
  • so array[index - 1] is the same as array[1] ,所以array[index - 1]array[1]相同,
  • array[1] holds the value 3 array[1]保存值3
  • so array[index - 1] + 2, is the equivalent of 3 + 2 , or 5所以array[index - 1] + 2,相当于3 + 2 ,或者5
  • So then, we assign array[index] which we know to represent the element array[2] ( which used to hold the value of 4 ) , now is assigned to hold the value 5 .那么,我们分配array[index] ,我们知道它代表元素array[2]它曾经保存4的值) ,现在分配给保存值5

values in array at end of 2nd time through the loop: 1,3,5,6,7第二次循环结束时数组中的值:1,3,5,6,7

etc.等等。

array      index  index-1  array[index-1] array[index-1]+2  array[index]
1,3,4,6,7  1      0        1              3                 array[1] = 3
1,3,4,6,7  2      1        3              5                 array[2] = 5
1,3,5,6,7  3      2        5              7                 array[3] = 7
1,3,5,7,7  4      3        7              9                 array[4] = 9
1,3,5,7,9  5      (exits for loop since condition fails)

final result: 1 3 5 7 9最终结果: 1 3 5 7 9

Also, you can use an 'online c compiler' to test code snippets.此外,您可以使用“在线 c 编译器”来测试代码片段。

Here's one: JDoodle这是一个: JDoodle

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

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