我正在尝试编写一个输出“n”(输入)斐波那契数

时间:2016-10-12 10:28:54

标签: c++ codeblocks fibonacci

我正在努力学习我的课程。它应输出n个Fibonacci数,每个都在一个新行上。如果Fibonacci数超出unsigned int的范围,您应该退出程序。此外,您应该在新行上打印显示多少个“n”的Fibonaccis。

以下是目前的代码:

#include<iostream>
#include<limits>

using namespace std;

int main()
{
  unsigned int n;

  cout << "Please enter the amount of fibonaccis you would like to compute:  " << endl;
  cin >> n;

  unsigned int next=1;
  unsigned int current=0;
  unsigned int c = current;
  unsigned int temp;
  unsigned int counter=1;

  //This bool returns true as soon as an overflow occurs
  bool overflow; 

 /*This bool checks, whether the newly computed 
    number is bigger than the previous number 
   (which may not be the case if an overflow occurs)*/

  bool nextBigger; 



  /*Somehow, I could only handle the first
    inputs by using "bruteforce".
    If I tried to combine it with the "main loop",
    it got all messy. */

  if(n==0)
  {
    std::cout << "0" << " of " << n << endl;
  }

  else if(n==1)
  {
     std::cout << "0" << endl << "1 of " << n << endl;
  }

  else if(n==2)
  {
     std::cout << "0" << endl << "1" << endl << "2 of " << n << endl;
  }

  else
  {   /* This for-loop increases (at least it should) a counter
         by one for each computation of a valid fibonacci number*/

      for(counter=1;counter<n;++counter)
      {

         overflow = (c > (std::numeric_limits<unsigned int>::max()-temp));

         if(!overflow && nextBigger)
         {
            cout << next << endl;

         }

         else
        {
           break; //If overflow or next number < previous number, exit program
        }

        temp = next; //temp is storage variable for next
        c = current; //storage variable for current
        next += current; //next is being altered: it becomes the new fibonacci number
        current = temp; //current gets value of temp( value of next before being altered)
   }

  nextBigger = (next > current);

  cout << counter << " of " << n << endl; //Output of how many fibonaccis were computed
}

  return 0;
}

所以这就是事情。我在CodeBlocks中对它进行了编程,它完美地工作了。但后来我尝试将其上传到Codeboard中(作为一项任务)。在Codeboard中它突然根本不起作用。也许它与不同的编译器有关,但我真的不知道如何解决这个问题。所以我很困惑,我会非常感谢任何提示,想法,更正或灵感。

(我是初学者,所以我希望代码是可以理解和可读的。我愿意接受建议的改进。)

1 个答案:

答案 0 :(得分:0)

查看你的代码,它似乎是if语句的主体

if(!overflow && nextBigger)
    {
       cout << next << endl;
    }

永远不会执行。也许在每次循环迭代时打印overflow和nextBigger的值,这样你就可以调试正在发生的事情。