1. 程式人生 > >[c語言]用遞迴和非遞迴求第n個斐波那契數

[c語言]用遞迴和非遞迴求第n個斐波那契數

程式碼

//1.1遞迴求第n個斐波那契數
#include<stdio.h>
int fib(int n)
{
 if(n<=2)
  return 1;
 else
  return fib(n-1)+fib(n-2);
}
int main()
{
 int n = 0;
 printf("請輸入你要查詢第幾個斐波那契數:\n");
 scanf("%d",&n);
 printf("第%d個斐波那契數為%d\n",n,fib(n));
 return 0;
}
//1.2非遞迴求第n個斐波那契數
#include<stdio.h>
int fib(int n)
{
int i = 0; int a = 1; int b = 1; int c = 1; for(i=0; i<n-2; i++) { c = a+b; a = b; b = c; } return c; } int main() { int n = 0; printf("請輸入你要查詢第幾個斐波那契數:\n"); scanf("%d",&n); printf("第%d個斐波那契數為%d\n",n,fib(n)); return 0; }