当前位置:网站首页>关于非递归和递归分别实现求第n个斐波那契数
关于非递归和递归分别实现求第n个斐波那契数
2022-07-28 16:31:00 【发疯的橙子】
斐波那契数列:1,1,2,3,5,8,13,21,34......
前两个数为1,当n>=2时,后面的斐波那契数为前面两个斐波那契数之和。
非递归方法实现第N个斐波那契数
#include <stdio.h>
int main()
{
int i = 0;
int a = 1;
int b = 1;
int c = a + b;
int n = 2;
scanf("%d", &n);
if (n > 2)//n<3则输出1,n>3进入循坏
{
for (i = 1; i <= n - 3; i++)//如第4个斐波那契数,只循坏1次.
{
a = b; //a=1
b = c; //b=2
c = a + b; //c=3
}
printf("%d\n", c);//输出第4个斐波那契数3
}
else
printf("%d\n", 1);//
return 0;
}递归方法实现第N个斐波那契数
#include <stdio.h>
int Fibonacci_number(int n)
{
if (n == 1)
{
return 1;
}
if (n == 2)
{
return 1;
}
else
return Fibonacci_number(n - 1) + Fibonacci_number(n - 2);
}
int main()
{
int n = 0;
scanf("%d",&n);
printf("第%d个斐波那契数是%d\n", n, Fibonacci_number(n));
return 0;
}递归画图演示
假如scanf输入的n是4,进入Fibonacci_number(n)函数体内

调用函数完后,return返回值,先返回最后一趟递归函数Fibonacci_number(n - 1)的值是1, Fibonacci_number(n - 2)是1,1+1=2;再返回第二趟递归返回2、1,最终返回主函数值为3.
最终输出:第4个斐波那契数是3.

边栏推荐
- 软件测试就业前景怎么样?
- Sed of shell programming
- 特殊质数js实现
- R语言画图/绘图/作图2
- 区分ES6的export与Nodejs的module.exports的区别
- 零基础软件测试培训可靠吗?
- ionic 中遇到的一些东西
- Encrypt the video and upload it to OSS to achieve high concurrent access
- Management of third-party technical services in product development
- [sqoop] sqoop 1.4.7 installation integration cdh5.13
猜你喜欢

Punctual atomic serial port protocol

Verilog daily question (vl4 shift operation and multiplication)
![[impala] [error reporting solution] impala cannot read or execute the parent directory of dfs.domain.socket.path](/img/8f/eb83ff3d5364a704957bc3217ccc2e.png)
[impala] [error reporting solution] impala cannot read or execute the parent directory of dfs.domain.socket.path

Vscode uses eslint prettier to format code automatically

Visual Object Class介绍PASCAL VOC数据集

2021 年全国大学生数据统计与分析竞赛

Master the key points of JVM interview
![[atlas] atlas compilation error sorting (all)](/img/bb/2ca51dffc7a09b378be4e581280246.png)
[atlas] atlas compilation error sorting (all)

Jdwp unauthorized rapid utilization

Wild pointer recurrence
随机推荐
Editor MAVON editor for offline use
dos命令大全 基础命令+网络的常用命令
Mqtt.fx connects to Alibaba cloud Internet of things platform
软件测试干货
漫谈测试平台—平台建设思路(上)
网上出现的js小数计算的除法优化
MySQL面试题大全(陆续更新)
Talk about what you know about publishing online (2)
strsplit()函数
在airtest中使用ocr反向识别文本内容
软件测试培训两个月可以就业吗?
生信人的20个R语言习题
软件测试和软件开发应该怎么选择?
新手通过自学转行软件测试难度大吗?
阿里P8架构师谈:成为架构师必须学好的七大知识点(含面试题)
Flat data to tree
100+ collection of medical image data sets
【 R语言—基础绘图】
MySQL download update
Insert text watermark in PDF