1 /* 2 递归函数: 3 函数自己调用自己就叫递归函数 4 递归可以实现循环 5 递归是神,迭代是人(迭代=循环) 6 缺点:需要暂存大量的数据,递归次数太多会占用大量内存空间 7 8 递归和迭代的区别 9 迭代是循环结构 10 递归是选择结构 11 12 细节: 13 1.自己调用自己 --变成死循环 14 2.添加结束条件 --避免死循环 15 3.最后从内层向外层进行计算 --得到结果 16 17 */ 18 19 20 #include "Recursion.h" 21 #include <iostream> 22 using namespace std; 23 24 25 26 //这里的递归就是个死循环,自己可以添加结束条件 27 void DoA() 28 { 29 cout <<"Hello"<<endl; 30 DoA(); 31 } 32 33 34 35 //这里就是有结束条件的循环啦 36 //int nStop=0; 37 //void DoB() 38 //{ 39 // nStop++; 40 // cout <<"Hello"<<endl; 41 // if (nStop == 10) 42 // { 43 // return; 44 // } 45 // DoB(); 46 //} 47 48 49 50 //用递归计算阶层 51 long Rank(int n) 52 { 53 if (0 == n) 54 { 55 return 1; 56 } 57 else 58 { 59 return n * Rank(n -1); 60 } 61 } 62 63 64 int main() 65 { 66 67 //DoA(); 68 //DoB(); 69 int nTest=5; 70 cout << Rank(nTest) <<endl; 71 system("pause"); 72 return 0; 73 }