函數語言程式設計 - 遞迴
自己呼叫自己的函式稱為遞迴函式,這種技術稱為遞迴。遞迴指令在遇到另一條指令阻止其進行之前會持續下去。
C++ 中的遞迴
以下示例展示了遞迴在面向物件程式語言 C++ 中的工作原理 −
#include <stdio.h>
long int fact(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, fact(n));
return 0;
}
long int fact(int n) {
if (n >= 1)
return n*fact(n-1);
else
return 1;
}
它會生成以下輸出
Enter a positive integer: 5 Factorial of 5 = 120
Python 中的遞迴
以下示例展示了遞迴在函數語言程式設計語言 Python 中的工作原理 −
def fact(n):
if n == 1:
return n
else:
return n* fact (n-1)
# accepts input from user
num = int(input("Enter a number: "))
# check whether number is positive or not
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
else:
print("The factorial of " + str(num) + " is " + str(fact(num)))
它會生成以下輸出 −
Enter a number: 6 The factorial of 6 is 720
廣告