2013-03-03 45 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