【发布时间】:2019-02-19 04:05:27
【问题描述】:
我不明白数组是如何被跟踪的。我觉得我知道它,但后来我又把它搞砸了。我知道值是如何交换的,但我仍然感到困惑。除了我的代码之外,我还把我的问题写成了 cmets。有人可以帮我追踪那部分吗?
#include <stdio.h>
int main()
{
int a[5]={1,2,3,4,5};
int i,j,temp;
for (j=1; j<5; j++)
for (i=0; i<5-j; i=i+2)
{
printf("%d %d\n",i,i+j); //I got this part right
temp = a[i]; //from here I get confused
a[i] = a[i+j]; //how is the addition inside working??
a[i+j] = temp; //temp = the index's value
}
for (i=0; i<5; i++)
printf("a[%d] = %d\n",i,a[i]);//what is i supposed to be here??
}
Output:
0 1
2 3
0 2
2 4
0 3
0 4
a[0] = 2 //from here on I get lost
a[1] = 1
a[2] = 5
a[3] = 4
a[4] = 3
【问题讨论】:
-
循环中的赋值顺序是用
a[i+j]交换a[i],在交换过程中使用temp作为中间值。