斐波那契系列(Fibonacci Series)

优质
小牛编辑
125浏览
2023-12-01

Fibonacci系列通过添加两个先前的数字来生成后续数字。 Fibonacci系列从两个数字开始--F 0和F 1 。 F 0和F 1的初始值可分别取0,1或1,1。

斐波那契系列满足以下条件 -

F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>

所以Fibonacci系列看起来像这样 -

F 8 = 0 1 1 2 3 5 8 13

或者,这个 -

F 8 = 1 1 2 3 5 8 13 21

算法 (Algorithm)

这个程序的算法很简单 -

START
   Step 1 → Take integer variable A, B, C
   Step 2 → Set A = 0, B = 0
   Step 3 → DISPLAY A, B
   Step 4 → C = A + B
   Step 5 → DISPLAY C
   Step 6 → Set A = B, B = C
   Step 7 → REPEAT from 4 - 6, for n times
STOP

伪代码 (Pseudocode)

procedure fibonacci : fib_num
   IF fib_num less than 1
      DISPLAY 0
   IF fib_num equals to 1
      DISPLAY 1
   IF fib_num equals to 2
      DISPLAY 1, 1
   IF fib_num greater than 2
      Pre = 1,
      Post = 1,
      DISPLAY Pre, Post
      FOR 0 to fib_num-2
         Fib = Pre + Post
         DISPLAY Fib
         Pre = Post
         Post = Fib
      END FOR
   END IF
end procedure

实现 (Implementation)

该算法的实现如下 -

#include <stdio.h>
int main() {
   int a, b, c, i, n;
   n = 4;
   a = b = 1;
   printf("%d %d ",a,b);
   for(i = 1; i <= n-2; i++) {
      c = a + b;
      printf("%d ", c);
      a = b;
      b = c;
   }
   return 0;
}

输出 (Output)

该方案的产出应该是 -

1 1 2 3