C ++程序使用递归查找斐波那契数
以下是使用递归的斐波那契数列的示例。
示例
#include <iostream>
using namespace std;
int fib(int x) {
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}
}
int main() {
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++;
}
return 0;
}输出结果
Enter the number of terms of series : 15 Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
在上面的程序中,实际的代码存在于函数“fib”中,如下所示:
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2));
}在该main()方法中,用户输入并fib()调用了多个术语。斐波那契系列打印如下。
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++;
}热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特