如何遞迴呼叫 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP