斐波那契函数的问题。 C ++ [英] Problem with fibonacci function. C++

查看:162
本文介绍了斐波那契函数的问题。 C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应返回数组的 n 位置。但不是价值,我只得到0。

  int fibonacci(int n)
{
int f [100];
f [0] = 0;
f [1] = 1;

for(int i = 2; i {
f [i] = f [i-2] + f [i-1]
}

return f [n];
}

int main()
{
cout<<斐波纳契(3);
返回0;
}

新代码:

<新的问题,它返回一个数字,然后它应该。例如,如果'n == 7'返回'13'而不是'8',它应该。

  int fibonacci(int n)
{
int f [100] = {0,1};

for(int i = 2; i <= n; i ++)
{
f [i] = f [i-2] + f [i-1]
}

return f [n-1];
}

int main()
{
cout<<斐波纳契(7);
返回0;
}


解决方案

code> f [n] ,你只能达到 i< n ,即 i == n-1
尝试返回 f [n-1]



编辑:Chris Lutz指出我的答案是如果你叫 fibonacci(0)



像许多人已经回答过的那样,最好的解决方案是循环直到 i <= n

除非你想要 fibonacci(3)返回斐波那契数列中的第三个元素,而不是第四个,在这种情况下 fibonacci(0)不会真的有意义,右边返回值应该是 f [n-1] ...仍然应该以某种方式处理 n == 0 ,应该是 n <0 n> 100 个案。



只要您检查正确的边界,就可以返回 f [n-1]

  int fibonacci(int n)
{
int f [100] = {0,1}; ((n <= 0)||(n> 100))
返回-1; //返回一些无效数字以告诉调用者他使用了错误的输入

for(int i = 2; i< n; i ++)//你可以使用i<这里
{
f [i] = f [i-2] + f [i-1];
}

return f [n-1];
}


Should return the n place of the array. But instead of the value I'm only getting 0.

int fibonacci(int n)
{
    int f[100];
    f[0] = 0;
    f[1] = 1;

    for (int i=2; i<n; i++)
    {
        f[i] = f[i-2] + f[i-1];
    }

    return f[n];
}

int main()
{
    cout << fibonacci(3);
    return 0;
}

New CODE:

New problem its returning one number further then it should. For example if 'n==7' its returning '13' not '8' like it should.

int fibonacci(int n)
{
    int f[100] = { 0, 1 };

    for (int i=2; i<=n; i++)
    {
        f[i] = f[i-2] + f[i-1];
    }

    return f[n-1];
}

int main()
{
    cout << fibonacci(7);
    return 0;
}

解决方案

well, you never set f[n], you only go up to i < n, that is, i == n-1. try returning f[n-1]

EDIT: as Chris Lutz pointed out my answer is no good as it would give an invalid result if you called fibonacci(0)

Like many have answered already, the best solution is to loop until i <= n
Unless, of course, you want fibonacci(3) to return the 3rd element in the fibonacci sequence and not the 4th, in which case fibonacci(0) wouldn't really make sense, and the right return value would be f[n-1]... still the n==0 case should be handled somehow, as should the n<0and the n>100 cases.

you can return f[n-1] as long as you check for the right boundaries:

int fibonacci(int n)
{
    int f[100] = { 0, 1 };

    if ((n <= 0) || (n > 100))
        return -1;//return some invalid number to tell the caller that he used bad input

    for (int i=2; i < n; i++) // you can use i < n here
    {
        f[i] = f[i-2] + f[i-1];
    }

    return f[n-1];
}

这篇关于斐波那契函数的问题。 C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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