函数的递归调用

介绍:一个函数在函数体内又调用了本身,称之为递归调用

例子:

 

 

①当在函数main内调用test(4)时,执行判断if,由于4>2,执行test(n-1),此时n=4,则传值为test(3)

②继续执行判断if,由于3>2,执行test(n-1),此时n=3,则传值为test(2)

③继续执行判断if,由于2>2不成立,不执行test(n-1),此时n=2,输出n=2,栈③销毁

执行完③后,要返回上一个栈②,执行printf,输出n=3,栈②销毁

执行完②后,再返回上一个栈①,执行printf,输出n=4,栈①销毁

最后返回给main

打印为:

 

 

内存图如下:

 

 

 

 

 

复制代码
 1 #include <stdio.h>
 2 
 3 void test(int n){
 4     if (n>2){
 5         test(n-1);
 6     }
 7     printf("\nn=%d", n);
 8 }
 9 
10 void main(){
11     test(4);
12 }
复制代码

对于过程,记住先进后出


 

例2:

 

 

 同样是函数main内调用test(4)

 

 

复制代码
 1 #include <stdio.h>
 2 
 3 void test(int n){
 4     if (n>2){
 5         test(n-1);
 6     }else{
 7     printf("\nn=%d", n);
 8     }
 9 }
10 
11 void main(){
12     test(4);
13 }
复制代码

注意函数条件的设置,防止出现无限递归导致栈溢出

如果执行到return语句,会直接返回到函数调用的位置继续执行,而函数内return语句后面的不再执行

 

 


 

实例:

 1.要求输入一个n,打印出斐波那契数列的第n位数字

复制代码
 1 #include <stdio.h>
 2 
 3 int test(int res){
 4     if(res == 1 | res == 2){
 5         return 1;
 6     }else{
 7         return test(res-1) + test(res-2);
 8     }
 9 }
10 //分析:如果n=1或者n=2,返回1,从n=3开始,返回前两个值相加
11 void main(){
12     int n = test(7);
13     printf("%d",n);
14 }
复制代码

2.已知f(1)=3,f(n)=2*f(n-1)+1,求f(n)

复制代码
 1 #include <stdio.h>
 2 
 3 int test(int res){
 4     if(res == 1){
 5         return 3;
 6     }else{
 7         return 2*test(res-1)+1;
 8     }
 9 }
10 
11 void main(){
12     int n = test(5);
13     printf("%d",n);
14 }
复制代码

3.

复制代码
 1 #include <stdio.h>
 2 
 3 //分析
 4 //day=10,有1个桃
 5 //day=9,有4个桃,(day10+1)*2=4
 6 //day=8,有10个桃,(day9+1)*2=10
 7 int m(int day){
 8     if(day == 10){
 9         return 1;
10     }else{
11         return (m(day+1)+1)*2;
12     }
13 }
14 
15 void main(){
16     int x = m(1);
17     printf("%d",x);
18 }
复制代码

 

posted @   Morning枫  阅读(230)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示