【问题标题】:I am not sure how the array of the code is being traced?我不确定如何跟踪代码数组?
【发布时间】: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作为中间值。

标签: c arrays loops trace


【解决方案1】:

为什么不在每个循环中打印整个数组,这样您就可以看到值是如何移动的,例如在步骤中交换 0,1 元素,因此数组是 {2,1,3,4,5 },然后 2,3 所以 {2,1,4,3,5},然后 0,2 所以 {4,1,2,3,5} , 2,4,=> {4,1,5,3 ,2}, 0,3 {3,1,5,4,2},0 4 {2,1,5,4,3}

【讨论】:

  • @ThomasKühn 可能是我理解错了问题,但他确实想知道数组的值是如何达到打印值的。也许你可以更好地澄清这个问题,谢谢
【解决方案2】:

我猜你对 C 编程了解不多。所以这里是关于数组的一点:

  1. 数组(此处为:int a[5]={1,2,3,4,5})是连续分配的内存块。
  2. 数组 a[n] 的大小为“n”(存储 n 个数组类型的值,此处为 int),索引从 0 到 n-1。这意味着从a[0]a[n-1] 访问n 个值中的每一个。
  3. 存在多维数组(请阅读!)。

这里给出的逻辑:

temp = a[i];   //temp gets a[i]'s value and not the value of i
a[i] = a[i+j];
a[i+j] = temp;

这是使用临时变量 temp 的标准 swap(a,b) 操作。只是这里的 'a' 和 'b' 是数组的元素。

循环的设计方式是在每次迭代中访问数组的不同元素。这会打乱数组。

很明显:

printf("a[%d] = %d\n",i,a[i]); // i here is the index used to access a's ith element

【讨论】:

    【解决方案3】:

    我发现我做错了什么。我只是想进行数学计算并更改该职位的价值。我必须打开空间并将旧号码移出以放入新号码。然后旧号码将进入剩余的空白空间。它实际上只是简单地交换,但以这种方式更好地看待它会有所帮助。

    所以在 {1,2,3,4,5} 中,如果我尝试将 a[3]=4 放入 a[1]=2,则值 4 将转到 a[1]。
    有 2 个的 a[1] 必须离开,而有 4 个的 a[3] 将进入。
    出来的 2 会在 a[3]=2 中之前 4 的位置。

    所以现在 a[1]=4 和 a[3]=2。 所以交换后的数组现在看起来像 {1,4,3,2,5}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多