使用递归在c ++中打印fibonacci系列 [英] printing fibonacci series using recursion in c++

查看:129
本文介绍了使用递归在c ++中打印fibonacci系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习c ++。我现在试着练习背诵。我想使用递归打印所有n(用户输入)斐波纳契数字,但它不工作。你可以帮帮我吗?谢谢!

I just started learning c++ by myself. I am trying to practice recusion now. I want to print all n(input by user) fibonacci numbers using recursion, but it does not work. Could you help me? Thank you!!

#include <iostream>
using namespace std;
int fibonacci(int n)
{   
    if (n==1)
    {
        return 1;
        cout<<1<<" ";
    }   
    else if (n==2)
    {
        return 1;
        cout<<1<<" ";
    }
    else
    {
        return (fibonacci(n-1)+fibonacci(n-2));
        cout<<fibonacci(n-1)+fibonacci(n-2)<<" ";
    }
}
int main()
{
    int n;
    cin>>n;
    fibonacci(n);
    return 0;
}


推荐答案

href =http://rosettacode.org/wiki/Fibonacci_sequence =nofollow> Fibonacci的Rosetta代码页,您会看到 F(0)== 0 F(1)== 1

If you look at Rosetta Code page for Fibonacci, you see that F(0) == 0 and F(1) == 1.

int fibonacci(int n)
{   

    if (n == 0)
    {
        return 0;
    }   
    else if (n == 1)
    {
        return 1;
    }
    else
    {
        return fibonacci(n-1) + fibonacci(n-2);
    }

    return fib;
}

在这种情况下,您有一个函数将计算斐波纳契数

In this case, you have a function that will calculate the fibonacci number at a specific position, right?

现在您需要计算它们,然后打印它们:

So now you need to calculate them and then print them:

int main()
{
    int n;
    cin >> n;

    if (n < 0)
    {
        return -1; // This means there was an error
    }

    for (int i = 1; i < n; ++i)
    {
        cout << fibonacci(i) << " ";
    }

    return 0;
}

请注意,这不是最有效的方式所有,但它有助于您了解递归的工作原理。

Note that this is not the most efficient way to do it at all, but it kinda helps you understand how recursion works.

这篇关于使用递归在c ++中打印fibonacci系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆