簡體   English   中英

任何人都可以解釋的C語言功能

[英]how to work function in c language anyone can explain please

在此代碼中,為什么n次打印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);
  }

在給出的代碼中,函數是遞歸的。 Count(n-1)反復調用該函數,直到條件if(n> 1)失敗。 因此,如果要將5傳遞給count函數。 它打印5次。

對於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)的遞歸調用以進行說明:

count(3)-打印(3)
(3> 1)為真---- count(2)-print(2)
(2> 1)是true ---- count(1)-print(1)
(1> 1)是錯誤的exec prev func調用
print(整數值為2)返回2
打印(整數值為3)
返回3
在遞歸樹中,查看代碼在何處打印值。

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

它打印出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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM