斐波那契数列 (Fibonacci Sequence) C++
Description
使用递归实现一个函数,打印斐波那契数列的第n
项。
斐波那契数列的定义如下:
-
F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)
递归思路:通过递归调用前两个数的和来计算当前的 Fibonacci 数字,直到达到递归的基本情况F(0)
或F(1)
。
Use recursion to implement a function to print then
-th Fibonacci number.
The Fibonacci sequence is defined as:
-
F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)
Recursive idea: Calculate the current Fibonacci number by recursively summing the previous two numbers, until reaching the base casesF(0)
orF(1)
.
Input
输入一个整数n
(0 ≤ n ≤ 20),代表要求的 Fibonacci 数列项。
Input an integern
(0 ≤ n ≤ 20), representing the position of the Fibonacci number to be computed.
Output
输出斐波那契数列的第n
项。
Output then
-th Fibonacci number.
Sample Input 1
6
Sample Output 1
8
#include<iostream>
using namespace std;
int F(int x)
{
if(x==0)
return 0;
else if (x==1)
return 1;
else
return F(x-1)+F(x-2);
}
int main()
{
int endnumber;
cin >> endnumber;
cout<< F(endnumber);
return 0;
}