我用三个例题来讲解函数递归
第一个 不使用临时变量计算字符串长度(用递归)
#include<stdio.h> #include<stdlib.h> int Strlen(char str[]){ if (str[0] == '\0'){ return 0; } return 1 + Strlen(str + 1); } int main(){ char str[] = "abcd"; int len = Strlen(str); printf("%d\n", len); system("pause"); return 0; }
我们如何理解这个函数呢 画图解决

第二个 不使用循环计算n!(用递归)
#include<stdio.h> #include<stdlib.h> int Factor(int n){ if (n == 1){ return 1; } return n * Factor(n-1); } int main(){ printf("%d\n", Factor(5)); system("pause"); return 0; }

第三个 不使用循环计算第n个斐波那契数列(用递归)
#include<stdio.h> #include<stdlib.h> int Fib(int n){ if (n == 1){ return 1; } if (n == 2){ return 1; } return Fib(n - 1) + Fib(n - 2); } int main(){ printf("%d\n", Fib(7)); system("pause"); return 0; }
实际中不推荐使用这种写法,重复计算量太大
运行时间过长,还是使用非递归效果更佳.
这个大家自己画图理解一下

浙公网安备 33010602011771号