2016-02-15 41 views
-1

我必須編寫代碼,將斐波那契數列顯示給用戶所需的術語數,並且還必須使用while循環。我不知道爲什麼這個代碼不工作。Fibonacci序列while循環

#include <stdio.h> 
#include <stdlib.h> 
int main (void) { 
    int max; 
    printf("Enter the max term of the Fibonacci Sequence:\n"); 
    scanf("%i", &max); 
    int a=0; 
    int b=0; 
    a=2; 

    while(a<max) { 
     if((a==0||a==1)) 
     { 
      printf("%i\n", &a); 
      ++a; 
     } 
     else if(a>1) 
     { 
      a=(a-1)+(a-2); 
      printf("%i\n", &a); 
      ++a; 
     } 
    } 
    return 0; 
} 
+3

你的邏輯似乎是錯誤的。 – Haris

+2

在你的'printf'語句中,你傳遞的是一個指針而不是'int'。擺脫'&'運算符,例如'printf(「%i \ n」,a);' –

+1

您需要同時使用'a'和'b'來完成這項工作。你不能只加倍'a'並減去2來得到下一個數字。 –

回答

0

在程序的開始(前while環)a爲2(見行a=2)。

而在while循環你如下:

a=(a-1)+(a-2); // a = 2-1+2-2 i.e. a = 1 

而且

++a; // a == 2 

於是,經過再次a==2之後。這個循環不會結束。

但它是技術問題。更重要的是,你正試圖計算斐波那契數列。在斐波那契數列中,每個後續數字都是前兩個數字的總和。但是在你的代碼中,不是前兩個數字的斐波那契數列,而是前兩個自然數。

你有變量b,因爲有人告訴你添加它。這是對的!請記住b中斐波那契數列的先前找到的元素。當你知道前一個元素和當前元素時,可以計算下一個元素。

0

你可以試試這個。

#include <stdio.h> 
#include <stdlib.h> 
int main (void) { 
    int max; 
    printf("Enter the max term of the Fibonacci Sequence:\n"); 
    scanf("%i", &max); 
    int n=0; 
    int a=0; 
    int b=1; 
    int next; 

    while(n<max) { 
     if (n <= 1) 
     { 
      next = n; 
      n++; 
     } 
     else 
     { 
     next = a + b; 
     a = b; 
     b = next; 
     n++; 
     } 
    printf("%d\n",next); 
} 
return 0; 

}

問題與您的代碼:

  1. 你是一個初始化= 2 =>它不會首先採取if循環 - '0' 將不被打印在您的結果。
  2. a =(a-1)+(a-2);即a = 1 那麼你正在做++ a; => a == 2.因此它再次循環與相同的a == 2。

因此它將打印相同的值並循環執行無限次。