在本教程中,我们将学习以下两种方法,以 C 编程语言显示 Fibonacci 序列:
1)使用for
循环
2)使用递归
使用循环的 Fibonacci 序列
一个简单的for
循环用于显示序列。程序提示用户输入项数,并显示具有相同项数的序列。
#include<stdio.h>
int main()
{
int count, first_term = 0, second_term = 1, next_term, i;
//Ask user to input number of terms
printf("Enter the number of terms:\n");
scanf("%d",&count);
printf("First %d terms of Fibonacci series:\n",count);
for ( i = 0 ; i < count ; i++ )
{
if ( i <= 1 )
next_term = i;
else
{
next_term = first_term + second_term;
first_term = second_term;
second_term = next_term;
}
printf("%d\n",next_term);
}
return 0;
}
输出:
Enter the number of terms: 8
First 8 terms of Fibonacci series:
0
1
1
2
3
5
8
13
使用递归显示 Fibonacci 序列的程序
这里我们使用用户定义的函数fibonacci_series()
,它递归调用自身,以显示输入的项数量的序列。
#include<stdio.h>
int fibonacci_series(int);
int main()
{
int count, c = 0, i;
printf("Enter number of terms:");
scanf("%d",&count);
printf("\nFibonacci series:\n");
for ( i = 1 ; i <= count ; i++ )
{
printf("%d\n", fibonacci_series(c));
c++;
}
return 0;
}
int fibonacci_series(int num)
{
if ( num == 0 )
return 0;
else if ( num == 1 )
return 1;
else
return ( fibonacci_series(num-1) + fibonacci_series(num-2) );
}
输出:
Enter number of terms: 6
Fibonacci series:
0
1
1
2
3
5