0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …
请注意,在第二个数字之后,序列中的每个数字都是前两个数字的和。斐波那契数列可以定义为:
F0 = 0,
F1 = 1,
FN = FN-1 + FN-2 对于所有 N≥2
int fib(int n)
{
if (n <= 0) //基本情况
return 0;
else if (n == 1) // 基本情况
return 1;
else
return fib(n - 1) + fib(n - 2);
}
下面的程序演示了该函数的应用,它显示了前 10 个斐波那契数列中的数字:
// This program demonstrates a recursive function that calculates Fibonacci numbers.
#include <iostream>
using namespace std;
int fib(int); // Function prototype
int main()
{
cout << "The first 10 Fibonacci numbers are: \n";
for (int x = 0; x < 10; x++)
cout << fib(x) << " ";
cout << endl;
return 0;
}
int fib (int n)
{
if (n <= 0) //base case
return 0;
else if (n == 1) //base case
return 1;
else
return fib(n - 1) + fib(n - 2);
}
程序输出结果:
The first 10 Fibonacci numbers are:
0 1 1 2 3 5 8 13 21 34
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有