递归函数就是直接或间接调用自身的函数。
C通过运行时堆栈支持递归函数的实现。(标准并未说明递归需要堆栈,但因为堆栈非常适合实现递归,所以很多编译器使用堆栈来实现递归。)
1、把一个整数从二进制形式转换为可打印的字符形式(如给出一个值4267,需要一次打印出字符‘4’、‘2’、‘6’、‘7’)
bi_to_ascii(int val){ int quotient; quotient = val/10; if(quotient){ bi_to_ascii(quotient); } putchar(val % 10 + '0'); }
很多地方使用阶乘和斐波那契数列来说明递归,但其实这并不高效
2 阶乘
2.1 递归法
long factorial(int n){ if(n<=0){ return 1; }else{ return n*factorial(n-1); } }
2.2 迭代法 【更有效】
long factorial(int n){ int re = 1; while(n>1){ re *= n; n--; } return re; }
3 斐波那契数列
3.1 递归法
long fabonacci(int n){ if(n==0){ return 0; }else if(n==1){ return 1; }else{ return fabonacci(n-1)+fabonacci(n-2); } }
3.2 迭代法【更有效】
long fabonacci(int n){ long re; long pre_re; long pre_pre_re; if(n==0){ return 0; } re = pre_re =1; while(n>2){ n--; pre_pre_re = pre_re; pre_re = re; re = pre_re + pre_pre_re; } return re; }
浙公网安备 33010602011771号