当前位置:网站首页>一本通1201——斐波那契数列
一本通1201——斐波那契数列
2022-07-27 05:04:00 【竹林居士-】
原题链接
http://ybt.ssoier.cn:8088/problem_show.php?pid=1201
【题目描述】
斐波那契数列是指这样的数列: 数列的第一个和第二个数都为1,接下来每个数都等于前面2个数之和。
给出一个正整数a,要求菲波那契数列中第a个数是多少。
【输入】
第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a(1<=a<=20)。
【输出】
输出有n行,每行输出对应一个输入。输出应是一个正整数,为斐波那契数列中第a个数的大小。
【输入样例】
4 5 2 19 1
【输出样例】
5 1 4181 1
审题
斐波那契数列第a项等于第a-1项加上第a-2项。只需递归求出前两项即可。
步骤
1.定义递归调用函数
int f(int x)
{
if(x==1 || x==2) return 1;//第一项和第二项值为1
else return f(x-1)+f(x-2); //递归调用
}
2.主函数
int main()
{
cin>>n;//共有n组
while(n--)//重复输入
{
cin>>a;
cout<<f(a)<<endl;//求第a项的值
}
return 0;
}完整代码
#include<iostream>
using namespace std;
int a,n;
int f(int x)
{
if(x==1 || x==2) return 1;//第一项和第二项值为1
else return f(x-1)+f(x-2); //递归调用
}
int main()
{
cin>>n;//共有n组
while(n--)//重复输入
{
cin>>a;
cout<<f(a)<<endl;//求第a项的值
}
return 0;
}新手,请多多指教
边栏推荐
- map结构
- mysql 取消外键关联约束
- GCC 编译选项
- JS如何判断一个对象是否属于一个类
- 进制的特性
- C语言指针入门详细介绍
- 后台实现spu管理
- First knowledge of C language -- constants and variables
- Multiplication sorting in torch, * & torch. Mul () & torch. MV () & torch. Mm () & torch. Dot () & @ & torch. Mutmal ()
- Program environment and preprocessing (Part 2): define, undef, command line compilation, conditional compilation, file inclusion (super full collation, recommended collection!!!
猜你喜欢

C language string function: StrCmp, strncpy, strncat, strncmp, strstr, strtok, strError

First knowledge of C language -- common data types

pytorch安装新坑

First knowledge of C language -- what is C language

Sharing force buckle-189. Three solutions of rotation array

初识C语言——初识指针

程序环境和预处理(上):一个程序是怎么成功运行的?

Li Hongyi machine learning team learning punch in activity day04 - Introduction to deep learning and back propagation mechanism

初始C语言——关键字static的作用

登录到主页功能实现
随机推荐
SQL (MySQL) rookie tutorial knowledge
qsort — c语言中自带的排序函数(附带void*、回调函数知识点
store redux在项目中的应用
C WPF uses listbox to implement ruler control
Hi3516DV300环境搭建
flask项目配置
Day6 --- SQLAlchemy进阶
c语言字符串函数上:strlen、strcpy、strcat
C language elementary level -- branch statement (if, switch)
C语言中堆内存介绍和管理
Carmaker quick start lesson 4 developing 48V P1 hybrid system
时间复杂度与空间复杂度
[codeworks round 801 div2 D tree queries] tree greedy conclusion
后台用户管理展示添加功能实现
程序环境和预处理(上):一个程序是怎么成功运行的?
pytorch安装新坑
flask一对多数据库创建,基础增删改查
Flask请求数据获取与响应
cmd命令和npm命令
C语言函数入门介绍