函数式编程 - 递归
自己调用自己的函数称为递归函数,这种技术称为递归。递归指令在遇到另一条指令阻止其进行之前会持续下去。
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
广告