2013-03-03 20 views
0

從字面上看,我被問到這個問題:「」斐波那契數列是0,1,1,2,3,5,8,13 ......;前兩個項是0和1,其後的每個項是前兩個項的和 - 即Fib [n] = Fib [n-1] + Fib [n-2]。使用這些信息,編寫一個C++程序,計算Fibonacci序列中的第n個數字,用戶在該程序中以交互方式輸入n。例如,如果n = 6,程序應該顯示值8.「斐波納契序列C++顯示一個/最大值

感謝上一個問題的答案,我把它放到了我的完整代碼中,我確實有一個循環,意味着用戶可以選擇它是否繼續該計劃或沒有。早前工作,但現在什麼也沒有發生。任何人都可以擺脫任何這光?謝謝

{int N; 

char ans = 'C'; 

while (toupper(ans) == 'C') 
{ 
    cout<<"This program is designed to give the user any value of the Fibonacci Sequence that they desire, provided the number is a positive integer.";//Tell user what the program does 

    cout<<"\n\nThe formula of the Fibonacci Sequence is; Fib[N] = Fib[N – 1] + Fib[N – 2]\n\n"; //Declare the Formula for the User 

    cout<<"Enter a value for N, then press Enter:"; //Declare Value that the User wants to see 

    cin>>N;//Enter the Number 

    if (N>1) { 
      long u = 0, v = 1, t; 

      for(int Variable=2; Variable<=N; Variable++) 
      { 
       t = u + v; 
       u = v; 
       v = t; 
      } //Calculate the Answer 

     cout<<"\n\nThe "<<N<<"th Number of the Fibonacci Sequence is: "<<t; //Show the Answer 
    } 

    if (N<0) { 
     cout<<"\n\nThe value N must be a POSITIVE integer, i.e. N > 0"; //Confirm that N must be a positive integer. Loop. 
    } 
    if (N>100) { 
     cout<<"\n\nThe value for N must be less than 100, i.e. N < 100. N must be between 0 - 100.";//Confirm that N must be less than 100. Loop. 
    } 
    if (N==0) { 
     cout<<"\n\nFor your value of N, \nFib[0] = 0"; //Value will remain constant throughout, cannot be caculated through formula. Loop. 
    } 
    if (N==1) { 
     cout<<"\n\nFor your value of N. \nFib[1]=1";//Value will remain constant throughout, cannot be caculated through formula. Loop. 
    } 

    cout << "\n\nIf you want to select a new value for N, then click C then press Enter. If you want to quit, click P then press Enter: "; 
    cin >> ans; 
} 


return 0; 

}

+6

將'cout'移出循環。 – 2013-03-03 20:33:18

+0

額外的'{'在其他之後? – exexzian 2013-03-03 20:36:45

回答

1

所有你需要的是下面放cout 2行。並且您不需要額外的{},但它不會造成傷害。

+0

好的,非常感謝你!你有可能向我解釋如何?只是想了解實際發生了什麼...... – Craig 2013-03-03 20:44:44

+0

正如你所看到的,你在循環中有'cout'。因此,每一個圓圈都會計入下一個值並打印出來。你需要的只是計數。循環後只打印最後一個值。 – Fuv 2013-03-03 20:48:09

+0

再次感謝!更新完整的代碼,如上所示,仍然是一個小問題... – Craig 2013-03-03 21:03:08

0

這是你的主循環:

for(int i=2; i<=N; i++) 
{ 
    t = u + v; 
    u = v; 
    v = t; 

    cout<<t<<"is your answer"; 
} 

這應該是顯而易見的,它是打印出你的答案就在每個循環傳球。

打印只需移動到循環外......所有的計算都完成後,你只會看到一次印刷:

for(int i=2; i<=N; i++) 
{ 
    t = u + v; 
    u = v; 
    v = t; 
} 
cout<<t<<"is your answer"; 

其他問題,我與你的代碼中看到:

你聲明函數:

unsigned long long Fib(int N); 

但它永遠不會定義或使用的。爲什麼這個聲明在這裏? (刪除)

你有多餘的一對大括號:

else { 
     { 
      unsigned long long u = 0, v = [....] 

你不需要緊跟多個支架支撐。

+0

謝謝,我已經整理過了。我也刪除了無符號long從「else { {unsigned long long u = 0,v = [...] 因爲它們似乎沒有任何東西,所以我從講師筆記中得到了這個函數。 ..爲什麼它不會有所作爲? – Craig 2013-03-03 20:58:25