Loading [MathJax]/extensions/tex2jax.js

搜尋此網誌

[C/C++][費氏數列(Fibonacci Sequence)]

費氏數列(Fibonacci Sequence),簡而言之就是下一項為前兩項的和,其結果為0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946...,在這邊是第0項為0,第一項為1,不過似乎有人是用第一項為1,第二項也為1,沒有第0項

以下是用遞迴的方式寫的

  1. /*
  2. * File Name: Fibonacci.c
  3. * Author: MH
  4. * Since 2011/05/16
  5. * Toolkit: Dev C++
  6. */
  7.  
  8. # include <stdlib.h>
  9. # include <stdio.h>
  10.  
  11. int fib(int n){
  12.  
  13.     if(n==0)
  14.         return 0;
  15.  
  16.     if(n==1)
  17.         return 1;
  18.  
  19.     return (fib(n-1)+fib(n-2));
  20.  
  21. }
  22.  
  23. int main(){
  24.  
  25.     int input, i;
  26.  
  27.     while(1){
  28.  
  29.         printf("The 0th number is 0, and the first number is 1\n");
  30.         printf("ex : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...\n\n");
  31.         printf("Please input an integer to show the last value of Fibonacci Sequence :\n");
  32.         scanf("%d", &input);
  33.         printf("\n");
  34.  
  35.         if(input<0)
  36.             printf("\nInput cannot less than 0\n\n");
  37.  
  38.         else{
  39.             for(i=0; i<=input; i++)
  40.                 printf("%d  ", fib(i));
  41.         }
  42.  
  43.         printf("\n\n");
  44.  
  45.         system("PAUSE");
  46.         system("CLS");
  47.  
  48.     }
  49.  
  50.     return 0;
  51.  
  52. }
  53.  

不過當然也有用迴圈的方法寫的

/*
* File Name: Fibonacci.c
* Author: MH
* Since 2011/05/16
* Toolkit: Dev C++
*/

# include <stdlib.h>
# include <stdio.h>

int main(){

    int n, i, n_2=0, n_1=1, fib;

    while(1){

        printf("The 0th number is 0, and the first number is 1\n");
        printf("ex : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...\n\n");
        printf("Please input an integer to show the last value of Fibonacci Sequence :\n");
        scanf("%d", &n);
        printf("\n");

        if (n == 0)
            fib = n_2;

        else if (n == 1)
            fib = n_1;

        else{

            for (i=2; i<=n; i++) {
                fib = n_2 + n_1;
                n_2 = n_1;
                n_1 = fib;
            }

            n_2 = 0;
            n_1 = 1;

        }

        printf("The Fibonacci Sequence is %d\n\n", fib);

        system("PAUSE");
        system("CLS");

    }

    return 0;
}

1 則留言: