当前位置:网站首页>函数递归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;
}
运行结果:
通过上面的例子,我们可以得到以下结论:
递归通常把一个复杂的问题简单化,它通过层层转化,将大型复杂的问题层层转化为一个相似的较小规模的问题来求解,递归策略只需要少量的程序就可以描述出解题过程中所需要的多次重复计算,大大的减少了程序的代码量。
边栏推荐
- 在 Excel 里使用 ODBC 读取 SAP BTP 平台上 CDS view 的数据
- Getting started with jmeter performance testing steps (performance testing tool jmeter)
- file contains vulnerabilities
- 使用docker搭建mysql主从
- Is the working process of the belt you know the story - actionreducerstore
- kernel syscore
- LeetCode - 025. 链表中的两数相加
- Android studio connects to MySQL and completes simple login and registration functions
- Three-tier architecture service, dao, controller layer
- A40i/T3 uboot启动时对PMU部分初始化
猜你喜欢
IDEA configure method annotation automatic parameters
After Effects 教程,如何在 After Effects 中修复曝光不足的镜头?
Use docker to build mysql master-slave
机器学习基本概念
Shengxin Weekly Issue 38
Docker实践经验:Docker 上部署 mysql8 主从复制
三六零与公安部三所发布报告:关基设施保护成为网络安全博弈关键
线性表的基本概念
LeetCode - 025. 链表中的两数相加
Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
随机推荐
Obsidian设置图床
The item 'node.exe' was not recognized as the name of a cmdlet, function, script file, or runnable program.
502 bad gateway causes and solutions
多线程学习笔记-2.final关键字和不变性
ApiPost is really fragrant and powerful, it's time to throw away Postman and Swagger
MySQL面试八股文(2022最新整理)
Exploring Plain Vision Transformer Backbones for Object Detection Paper Reading Notes
带有对称约束切换线性系统的结构可控性
busybox之reboot命令流程分析
apisix-Getting Started
Is the working process of the belt you know the story - actionreducerstore
St. Regis Takeaway Project: New dishes and dishes paged query
MySQL百万数据优化总结 一
CameraToolUnity中两种摄像机的两种观察控制方式
Use Excel to read data exposed by SAP ABAP CDS View through ODBC
Selenium自动化测试之Selenium IDE
Docker installs canal and mysql for simple testing and achieves cache consistency between redis and mysql
ESP8266-Arduino编程实例-PIR(被动红外)传感器驱动
串的基本概念与操作
字符函数和字符串函数