当前位置:网站首页>一本通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;
}新手,请多多指教
边栏推荐
- User login - and create and verify SMS verification code
- Seckill system design
- First knowledge of C language -- constants and variables
- 初识C语言——什么是C语言
- ES6中new一个箭头函数会怎样
- How to get started quickly and strengthen learning?
- [C language switch branch statement and loop statement]
- My first blog
- 路由的配置和前往登录首页进行发送请求
- Li Hongyi machine learning team learning punch in activity day04 - Introduction to deep learning and back propagation mechanism
猜你喜欢

强制登录,七牛云上传图片

Li Hongyi machine learning team learning punch in activity day02 --- return

Sharing force buckle-189. Three solutions of rotation array

Hi3516dv300 environment setup

C language elementary level -- branch statement (if, switch)

Li Hongyi machine learning team learning punch in activity day06 --- convolutional neural network

初识C语言——常见的数据类型

DNSmasq使用总结

初识C语言——初识指针

权限的配置,组件传值
随机推荐
c语言字符串函数上:strlen、strcpy、strcat
My first blog
Introduction and management of heap memory in C language
mysql 取消外键关联约束
DNSmasq使用总结
MySQL cancels the foreign key Association constraint
cmd命令和npm命令
图片上传的逻辑
块,行内块元素之间存在间隙
C语言初阶——分支语句(if,switch)
Looking at the PK of alphago and Li Shishi from a deep perspective
let、const、var之间的用法以及区别
C语言中堆内存介绍和管理
程序环境和预处理(上):一个程序是怎么成功运行的?
Li Hongyi machine learning team learning punch in activity day04 - Introduction to deep learning and back propagation mechanism
Program environment and preprocessing (Part 1): how does a program run successfully?
Day6 --- SQLAlchemy进阶
Package JWT
Flask框架创建项目初期总结
Day4 --- Flask 蓝图与Rest-ful