2017-04-08 78 views
-3

我爲While Loop製作過,但無法使用For。如何使用For循環制作斐波納契數列?

我試過很多東西。

我試圖改變我的while循環,但我沒有成功。我也在網上進行了研究,但所有的答案都是錯誤的。

+1

您的解決方案是在這裏(用JavaScript編寫的)http://stackoverflow.com/a/7944251/7603852 – Ariyan

+0

你應該尋找一個while循環轉換爲等效的for循環的一些例子,因爲所有能,並嘗試自己完成你的任務,完成這樣一個任務的目的。你試過一些解決方案?發佈他們,你會得到指導。這就是爲什麼。 – schulmaster

回答

0
#include <iostream> 
using namespace std; 

int main() 
{ 
    int n, t1 = 0, t2 = 1, nextTerm = 0; 

    cout << "Enter the number of terms: "; 
    cin >> n; 

    cout << "Fibonacci Series: "; 

    for (int i = 1; i <= n; ++i) 
    { 
     // Prints the first two terms. 
     if(i == 1) 
     { 
      cout << " " << t1; 
      continue; 
     } 
     if(i == 2) 
     { 
      cout << t2 << " "; 
      continue; 
     } 
     nextTerm = t1 + t2; 
     t1 = t2; 
     t2 = nextTerm; 

     cout << nextTerm << " "; 
    } 
    return 0; 
} 
+0

請爲您的問題添加更多的datail –