斐波那契数列c++实现

递归补充

编写递归数列int fib(int n),在主程序中输入n的值,调用fib函数计算fibonacci级数
公式自行百度:

#include <iostream>
using namespace std;

int fib(int n)
{
    
    
    cout<<"Processing fib("<<n<<")...";
    if(n<3)
    {
    
    
        cout<<"Return 1!\n";
        return (1);
    }
    else
    {
    
    
        cout<<"Call fib("<<n-2<<")and fib("<<n-1<<").\n";
        return(fib(n-2)+fib(n-1));
    }

}
int main()
{
    
    
    int n,answer;

    cout<<"Enter number:";

    cin>>n;

    cout<<"\n\n";

    answer=fib(n);

    cout<<answer<<"is the"<<n<<"the Fibonacci number\n";

    return 0;

}

猜你喜欢

转载自blog.csdn.net/niko02/article/details/121469609