在同一函数中调用函数时,在C++中称为递归。调用相同函数的函数称为递归函数。
调用自身并且在函数调用后不执行任何任务的函数称为尾递归。在尾部递归中,我们通常使用return语句调用相同的函数。
让我们看一个简单的递归示例。
recursionfunction(){ recursionfunction(); //将值传递给函数 }
让我们看一个示例,该示例使用C++语言的递归来打印阶乘数。
#include<iostream> using namespace std; int main() { int factorial(int); int fact,value; cout<<"Enter any number: "; cin>>value; fact=factorial(value); cout<<"Factorial of a number is: "<<fact<<endl; return 0; } int factorial(int n) { if(n<0) return(-1); /*错误的值*/ if(n==0) return(1); /*终止条件*/ else { return(n*factorial(n-1)); } }
输出:
Enter any number: 5 Factorial of a number is: 120
通过下图我们可以理解上述递归方法调用程序:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕