函数递归

函数递归 首页 / 函数式入门教程 / 函数递归

调用自身的函数称为递归函数,而此技术称为递归,递归指令继续,直到另一条指令阻止它为止。

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   

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Service Mesh实践指南 -〔周晶〕

邱岳的产品实战 -〔邱岳〕

如何做好一场技术演讲 -〔极客时间〕

玩转Spring全家桶 -〔丁雪丰〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

高楼的性能工程实战课 -〔高楼〕

运维监控系统实战笔记 -〔秦晓辉〕

超级访谈:对话道哥 -〔吴翰清(道哥)〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)