如何在c语言中工作,任何人都可以解释

时间:2016-11-23 06:19:26

标签: c

在此代码中为什么n次打印n次,任何人都可以解释,为什么打印调用n次

 int count(int n){
        print("%d" , n);
             if(n>1){
                  count(n-1);
              }
        print("Integer value is %d\n" , n);
     return n;
    }
   int main(){
     count(3);
  }

3 个答案:

答案 0 :(得分:1)

在给出的代码中,函数是递归的。 Count(n-1)一次又一次地调用该函数,直到条件if(n> 1)失败。所以,如果你将5传递给count函数。它打印5次。

答案 1 :(得分:1)

对于count(n),您的代码将打印出如下内容:

n,n-1,n-2....1 Integer value is 1
Integer value is 2
Integer value is 3
....
....
Integer value is n

现在让我们看一下原因,找到count(3)的递归调用来说明:

计数(3) - 印刷(3)
(3> 1)为真--- count(2) - print(2)
   (2> 1)为真--- count(1) - print(1)
(1> 1)是假exec prev func call
print(整数值为2)                                       返回2
            print(整数值为3)
           返回3
在递归树中,查看代码打印值的位置。

Input: count(3)
Output:
321Integer value is 1
Integer value is 2
Integer value is 3

答案 2 :(得分:0)

打印出6次。这是因为程序被告知了。让我们将函数调用插入主代码中:

int count(3) // call with 3
{
  print("%d" , 3);                      // prints 3
  if(3>1)
  {
    count(3-1);
  }
  print("Integer value is %d\n" , n);   // prints 3
  return n;
}

再次插入通话:

int count(3) // call with 3
{
  print("%d" , 3);                          // prints 3
  if(3>1)
  {
    // count(3-1)
    {
      print("%d" , 2);                      // prints 2
      if(2>1)
      {
        count(2-1);
      }
      print("Integer value is %d\n" , 2);   // prints 2
      return 2;
    }
  }
  print("Integer value is %d\n" , 3);       // prints 3
  return 3;
}

再次:

int count(3) // call with 3
{
  print("%d" , 3);                          // prints 3
  if(3>1)
  {
    // count(3-1)
    {
      print("%d" , 2);                      // prints 2
      if(2>1)
      {
        // count(2-1);
        {
          print("%d" , 1);                      // prints 1
          if(1>1)                            // is false, no recursion any more
          {
            // count(1-1);
          }
          print("Integer value is %d\n" , 1);   // prints 1
          return 1;
        }
      }
      print("Integer value is %d\n" , 2);   // prints 2
      return 2;
    }
  }
  print("Integer value is %d\n" , 3);       // prints 3
  return 3;
}
相关问题