在我的C程序中,为什么我的跟踪循环和实际输出不同?

时间:2019-02-17 02:16:08

标签: c arrays loops trace

  1. 跟踪以下程序的执行?将打印数组的最终值是什么? 我必须跟踪以下C代码并编写输出。我运行了程序,输出结果与预期的不同。很可能我没有正确地找到它,但是我找不到我做错了什么。

*我没有写代码。该代码已包含在问题中。

#include <stdio.h>
#include <math.h>

int main()
{
    int a[7]={2,0,0,0,0,0,0};
    int i=1;

    for (i=1; i<7; i++)
    {

       if (i<3)
          a[i] = a[i-1]+i+1; //when i=1, a[1]= a[1-1]+1+1 -> a[0]+1+1 -> 2+1+1=4
                             //a[1] is now 4
                             //when i=2, a[2]= a[2-1]+1+1 -> a[1]+1+1 -> 4+2+1=7
                             //a[2] is now 7
       else if (i<5) 
          a[i] = a[i-2]+1;   //when i=3, a[3]= a[3-2]+1 -> a[1]+1 -> 4+1=6 
                             //a[3] is now 6 but it should be 11??? 11
                             //when i=4, a[4]= a[4-1]+1 -> a[2]+1 -> 7+1=8
                             //a[4] is now 8 but it should be 16??? 16

       else
          a[i] = a[i-2]*i-2; //when i=5, a[5]= a[5-2]*5-2 -> a[3]*3 -> 6*3= 18 
                             //a[5] is now 18 but it should be 22???
                             //when i=6, a[6]= a[6-1]*6-2 -> a[5]*4 -> 18*4= 72
                             //a[6] is now 8 but it should be 29????

    }
    for (i=0; i<7; i++)
       printf("a[%d] = %d\n",i,a[i]); //prints a[0] = 2 first because i=0 in the above loop
}

实际输出:

a[0] = 2
a[1] = 4
a[2] = 7
a[3] = 11
a[4] = 16
a[5] = 22
a[6] = 29

1 个答案:

答案 0 :(得分:1)

我复制了您的代码并运行了,这是我的输出:

a[0] = 2
a[1] = 4
a[2] = 7
a[3] = 5
a[4] = 8
a[5] = 23
a[6] = 46