如何遞迴呼叫 C# 方法?


要遞迴呼叫 C# 方法,可以嘗試執行以下程式碼。此處,我們將使用 display() 遞迴函式查詢一個數字的階乘。

如果值為 1,則返回 1,因為階乘是 1。

if (n == 1)
return 1;

如果不是,則如果要獲得 5! 的值,將為以下迭代呼叫遞迴函式

Interation1: 5 * display(5 - 1);
Interation2: 4 * display(4 - 1);
Interation3: 3 * display(3 - 1);
Interation4: 4 * display(2 - 1);

以下是遞迴呼叫 C# 方法的完整程式碼。

示例

 現場演示

using System;
namespace MyApplication {
   class Factorial {
      public int display(int n) {
         if (n == 1)
         return 1;
         else
         return n * display(n - 1);
      }
      static void Main(string[] args) {
         int value = 5;
         int ret;
         Factorial fact = new Factorial();
         ret = fact.display(value);
         Console.WriteLine("Value is : {0}", ret );
         Console.ReadLine();
      }
   }
}

輸出

Value is : 120

更新時間:2020 年 6 月 23 日

258 次瀏覽

助力你的 職業生涯

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.