当前位置:网站首页>函数递归1.0
函数递归1.0
2022-07-31 12:10:00 【林深方见鹿】
首先我们简单来认识一下什么是递归,递归就是一个过程或函数在其定义或说明中有直接或者间接调用自身的一种方法,递归的主要思考方式在于把大事化小。
递归有两个必要条件:存在限制条件,当满足限制条件时,递归便会停止;每次递归调用都会越来越接近这个限制条件。
举例1:
输入一个无符号整形数,按照顺序打印每一位数字。比如输入1234,打印1 2 3 4.
下面来展示一下我的思考过程:
如果这个数只有个位数,那么直接打印就可以了,如果大于九,就需要我们想办法来解决了,怎么解决呢?我们要得到单独的一个数字,最简单的办法就是直接除以10,然后再对10取模,就得到了单独的一位数,想到这一步,就继续想着要找到一个合适的途径去实现,递归是一种很好的方式,通过递归调用,调用到最接近限制条件,到达最底层,然后再一步步返回上一层,回到最顶层,最后得到我们想要的结果。
我们来看一下程序:
#include<stdio.h>
void print(int n)
{
if (n > 9)
print(n / 10);
printf("%d ", n%10 );
}
int main()
{
int num;
printf("请输入一个整型值:\n");
scanf("%d", &num);
print(num);
return 0;
}运行结果:

举例2:
用递归求阶乘。
我们知道,0和1的阶乘等于1,当n大于1时,n的阶乘等于n-1的阶乘乘以n,所以我们就可以借助递归来实现求阶乘。
//求n的阶乘
#include<stdio.h>
int factorial(int n)
{
if (n <= 1)
return 1;
else
return n*factorial(n - 1);
}
int main()
{
int n = 5;
int res = factorial(n);
printf("%d \n", res);
return 0;
}运行结果:

举例3:
求第n个斐波那契数(不考虑溢出)
//求第n个斐波那契数(不考虑溢出)
#include<stdio.h>
int fib(int n)
{
if (n <= 2)
return 1;
else
return (fib(n - 1) + fib(n - 2));
}
int main()
{
int n = 7;
int res = fib(7);
printf("%d ", res);
return 0;
}运行结果:

通过上面的例子,我们可以得到以下结论:
递归通常把一个复杂的问题简单化,它通过层层转化,将大型复杂的问题层层转化为一个相似的较小规模的问题来求解,递归策略只需要少量的程序就可以描述出解题过程中所需要的多次重复计算,大大的减少了程序的代码量。
边栏推荐
- PAT exam summary (exam experience)
- JVS函数公式使用场景介绍
- Wearing detection and action recognition of protective gear based on pose estimation
- 立方体IV(暑假每日一题 10)
- A40i/T3 uboot启动时对PMU部分初始化
- R 语言data.frame 中的另一行中减去一行
- 使用 Excel 读取 SAP ABAP CDS View 通过 ODBC 暴露出来的数据
- Chrome开发自定义右键菜单实现快速跳转到指定页面
- 想吃菌子,当然是自己上山找了
- Structural controllability of switched linear systems with symmetry constraints
猜你喜欢

After class, watching the documentation and walking back to the lab, I picked up the forgotten SQL operators again

普林斯顿微积分读本03第二章--编程实现函数图像绘制、三角学回顾

字符函数和字符串函数

Distributed id solution

AWS Amazon cloud account registration, free application for 12 months Amazon cloud server detailed tutorial

TOGAF10标准读书会第2场活动精彩继续,高光时刻回顾!

Read through the interface to call the artifact RestTemplate

JVS开发套件产品定位

Docker实践经验:Docker 上部署 mysql8 主从复制

MySql模糊查询大全
随机推荐
这款悄然崛起的国产API接口管理工具,你一定要晓得
Wearing detection and action recognition of protective gear based on pose estimation
chroot命令
LeetCode - 025. 链表中的两数相加
建情人节表白网站(超详细过程,包教包会)
Docker安装canal、mysql进行简单测试与实现redis和mysql缓存一致性
订song餐系统
SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块
am335x 看门狗驱动&看门狗应用例程序
给你一个大厂面试的机会,你能面试上吗?进来看看!
Comparison of ipv4 and ipv6 (IPV4)
busybox之reboot命令流程分析
Service discovery of kubernetes
Qt鼠标穿透
最近两个月谷歌 ad 掉的厉害
In PLC communication error or timeout or download the prompt solution of the model
Use docker to build mysql master-slave
基于姿态估计的护具佩戴检测与动作识别
WPF中TabControl动态获取当前选中的TabItem
「R」使用ggpolar绘制生存关联网络图