Fibonacci数列基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
C语言中的斐波那契数列: 对于斐波那契数列,下一个数字是前两个数字的和,例如0、1、1、2、3、5、8、13、21等。斐波那契数列的前两个数字是0和1、
有两种方法可以编写斐波那契系列程序:
无递归的斐波那契数列
使用递归的斐波那契数列
没有递归的C语言中的斐波那契数列
让我们看看没有递归的C语言中的斐波那契数列程序。
#include<stdio.h> int main() { int n1=0,n2=1,n3,i,number; printf("Enter the number of elements:"); scanf("%d",&number); printf("\n%d %d",n1,n2);//printing 0 and 1 for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed { n3=n1+n2; printf(" %d",n3); n1=n2; n2=n3; } return 0; }
输出:
Enter the number of elements:15 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
在C中使用递归的斐波那契数列
让我们看看在C中使用递归的斐波那契数列程序。
#include<stdio.h> void printFibonacci(int n){ static int n1=0,n2=1,n3; if(n>0){ n3 = n1 + n2; n1 = n2; n2 = n3; printf("%d ",n3); printFibonacci(n-1); } } int main(){ int n; printf("Enter the number of elements: "); scanf("%d",&n); printf("Fibonacci Series: "); printf("%d %d ",0,1); printFibonacci(n-2);//n-2 because 2 numbers are already printed return 0; }
输出:
Enter the number of elements:15 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377