我如何做fibonaci序列低于1000? [英] How I do fibonaci sequence under 1000?

查看:253
本文介绍了我如何做fibonaci序列低于1000?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;
void main()
{
  int i = 0;
  while (i < 1000)
  {
      int TEMP = i * 2;
      cout << i << endl;
      TEMP = i;
      i = i +1;
      // ???
  }

  return;
}

我很困惑? :(

推荐答案

首先,您应该检查您是否明白斐波纳契数字

First you should check that you understand the definition of the Fibonacci numbers.


根据定义,前两个斐波纳契数字是0和1,每个剩余的数字是前两个的总和。一些源省略了初始的0,而是以两个1开始序列。

By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.

你需要两个变量来记住状态,而不只是一个你想做的事情,你不需要乘以两个变量,你只需要添加两个变量。

You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.

#include <iostream>
using namespace std;
int main()
{
    int i = 0;
    int j = 1;
    while (i < 1000)
    {
        /* Print a number. */
        cout << i << endl;

        /* Set j to the sum of i and j, and i to the old value of j. */
        int TEMP = j;
        j += i;
        i = TEMP;
    }
    return 0;
}

这篇关于我如何做fibonaci序列低于1000?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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