C ++ Fibonacci序列

时间:2018-01-22 11:16:33

标签: c++ c++14 fibonacci

我想要制作的程序应该计算并显示斐波纳契序列的每个条目,直到40日。

我相信我已经完成了这项任务。问题是:在数字1和数字2之后,序列似乎重置自身并在序列中留下后面的每个数字1位。

这是代码:

#include <iostream>
using namespace std;

int main()
{
    int a = 0;
    int b = 1;
    for (int i = 0; i < 40; ++i)
    {
        if (i==1)
        {
            cout << i << " " << b << endl;
        }
        else if (i==2)
        {
            cout << i << " " << b*2 << endl;
        }
        else
        {
            int c = a + b;
            a = b;
            b = c;
            cout << i << " " << c << endl;
        }
    }
    return 0;
}

我预先编写了序列中的前几个数字,因为我无法让它们正常工作,但在这样做之后,它似乎摒弃了程序的其余部分。

代码的输出是:

0 1
1 1
2 2
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144
13 233
14 377
15 610
16 987
17 1597
18 2584
19 4181
20 6765
21 10946
22 17711
23 28657
24 46368
25 75025
26 121393
27 196418
28 317811
29 514229
30 832040
31 1346269
32 2178309
33 3524578
34 5702887
35 9227465
36 14930352
37 24157817
38 39088169
39 63245986

4 个答案:

答案 0 :(得分:4)

似乎我在创建帖子后立即解决了这个问题。

我决定尝试将序列(0)中的第一个条目预先编程为1,并完全删除序列中的其他预编程部分。这解决了整个问题。

这是工作代码:

#include <iostream>
using namespace std;

int main()
{
    int a = 0;
    int b = 1;

    for (int i = 0; i < 40; ++i)
    {
        if (i == 0)
        {
            cout << i << " " << b << endl;
        }
        else
        {
            int c = a + b;
            a = b;
            b = c;
            cout << i << " " << c << endl;
        }
    }
    return 0;
}

答案 1 :(得分:2)

您忘记为第二种情况设置b = 2

因此,当c时,a使用0之前的c = a+b值。 因此,a = 1 = 0 + 2 = 2

在第二种情况下设置else if (i==2) { a = 1 // This cout << i << " " << b*2 << endl; }

try:
    r = requests.get('https://sensitive:passw0rd@what.ever/')
    r.raise_for_status()
except requests.HTTPError:
    logging.exception("Failed to what.ever")

答案 2 :(得分:0)

我预编程序列中的前几个数字 ..如果你想这样做,以下可能是另一种方法..

#include <iostream>
using namespace std;

int main()
{
    int a = 0;
    int b = 1;

    cout << 0 << " " << a << endl;//simply display the preprogrammed numbers
    cout << 1 << " " << b << endl;

    for (int i = 2; i < 40; ++i)//apply the formula for remaining elements
    {
        int c = a + b;
        a = b;
        b = c;
        cout << i << " " << c << endl;
    }
    return 0;
}

答案 3 :(得分:0)

在您的计划中尝试以下更改。

#include <iostream>
using namespace std;

int main() {
    int a = 0;
    int b = 1;
    for (int i = 0; i < 40; ++i)
    {
        if (i==0)
        {
            cout << i << " " << a << endl;
        }
        else if (i==1)
        {
            cout << i << " " << b << endl;
        }
        else
        {
            int c = a + b;
            a = b;
            b = c;
            cout << i << " " << c << endl;
        }
    }
    return 0;
}