C language - three different methods of finding the Fibonacci sequence of the first 20 items

Task 4: Program to output the Fibonacci sequence of the first 20 items

  1. Fibonacci sequence: introduced by taking rabbit breeding as an example, it is also called "rabbit sequence", which refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34,
  2. It is known that the first two values ​​are 0 and 1. Starting from the third item, each item is the sum of the previous two values. That is: 1, 1, 2, 3, 5, 8,...

Method 1: Array accumulation (save each value in the array)

#include "stdio.h"
int main(){
    
    
//编程输出前20项的斐波那契数列
//已知前两项值为0、1,从第3项开始,每一项都是前两项数值之和.即:1,1,2,3,5,8
    int num[20]={
    
    1,1};
    printf("斐波那契数列:=====================================\n");
    for (int j = 2; j < 22; j++) {
    
    	//j < 22   ,此处数组不会越界 ,因为输出的是num[j-2];
        num[j] = num [j-1] + num[j-2];
        printf("num[%d]=%d\n",j-2,num[j-2]);
    }
}

operation result
insert image description here

Method 2: Variable coverage (overwrite a variable value)

#include "stdio.h"
int main(){
    
    
//编程输出前20项的斐波那契数列
//已知前两项值为0、1,从第3项开始,每一项都是前两项数值之和.即:1,1,2,3,5,8
    int a=1,b=1,next;//next表示a+b;
    printf("斐波那契数列:=====================================\n");
    printf("第1项为:1\n");
    printf("第2项为:1\n");
    for (int i = 0; i < 18; ++i) {
    
    
        next = (a+b);a = b;b =next;
        printf("第%d项为:%d\n",i+3,next);
    }

}

operation result:
insert image description here

Method 3: Variable coverage (overwrite two variable values)

It only needs to loop 10 times to output the first 20 items

#include "stdio.h"
int main(){
    
    
//编程输出前20项的斐波那契数列
//已知前两项值为0、1,从第3项开始,每一项都是前两项数值之和.即:1,1,2,3,5,8
    int a=1,b=1;
    printf("斐波那契数列:=====================================\n");
    for (int i = 0; i < 10; ++i) {
    
    
        printf(" %d %d ",a,b);
        a=a+b;
        b=a+b;
    }
}

operation result

Portal ---- more content:
C Language Algorithm Problem Set - Review 1

Guess you like

Origin blog.csdn.net/qq_49612126/article/details/125826234