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 2026祝福语简短创意牛
17 朋友祝福语两字简短
18 餐前仪式祝福语简短