6
#include <iostream>

using namespace std;

int main()
{
    int num1 = 0;
    int num2 = 1;
    int num_temp;
    int num_next = 1;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        cout << num_next << "  ";
        num_next = num1 + num2;
        num1 = num2;
        num_temp = num2;
        num2 = num_next - num1;
        num1 = num_temp;
    }
    return 0;
}

我必须输出第一个“n”斐波那契数,但是我认为逻辑上存在一些问题。我不知道我做错了什么。前 3 或 4 个元素是正确的,但随后出现问题......

预期:
对于n=9

0, 1, 1, 2, 3, 5, 8, 13, 21

实际的:

1 1 1 1 1 1 1 1 1

4

15 回答 15

7
#include <iostream>

using namespace std;

int main()
{
    int num1 = 0;
    int num2 = 1;
    int num_temp;
    int num_next = 1;
    int n;
    cin >> n;
    if (n>=1)
        cout << 0 << " ";
    if (n>=2)
        cout << 1 << " ";
    for (int i = 0; i < n-2; i++){
        num_next = num1 + num2;
        cout << num_next << " ";
        num1 = num2;
        num2 = num_next;
    }
    cout << endl;
    return 0;
}
于 2013-11-01T00:00:50.333 回答
3

试试这个。这有点不同,但会让你到达那里。

#include <iostream>

using namespace std;

int main()
{
   int input(0), Alpha(0), Beta(1), Total(1);  
   cout << "Please input a top number: "; 
   cin >> input; 

   for(int i = 0; i <= input; i++)
   {
      cout << Total << endl; 
      Total = Alpha + Beta; 
      Alpha = Beta;
      Beta = Total; 
   }
} 
于 2013-11-01T00:04:05.237 回答
2

这是我的版本。

它或多或少与以前的示例相同,但我想展示环形缓冲区的使用。

// Study for algorithm that counts n:th fibonacci number
// Fibonacci[1] == 1 and Fibonacci[2] == 1 (and Fibonacci[0] == 0)
// Fibonacci[n] = Fibonacci[n-1] + Fibonacci[n-2]                      

#include <cstdio>
#include <iostream>
#include <cstdlib>

int main(int argc, const char* argv[])
{

  // not counting trivial Fibonacci[0]
  if(argc != 2 || atoi(argv[1]) < 1){
    std::cout << "You must provide one argument. Integer > 0" << std::endl;
    return EXIT_SUCCESS;
  }

  // ring buffer to store previous two fibonacci numbers, index it with  [i%2]
  // seeded with Fibonacci[1] and Fibonacci[2]
  // if you want to count really big fibonacci numbers, you have to make your own type for
  // buffer variable
  // this type overflows after [93] with my macbook
  unsigned long long int buffer[2]={ 1, 1 };

  // n:th Fibonacci                                                             
  unsigned int fn = atoi(argv[1]);

  // count loop is used if seeked fibonacci number is gt 2                      
  if(fn > 2){
    for(unsigned int i = 2; i < fn; ++i){                                
      buffer[i%2] = buffer[(i-1)%2] + buffer[(i-2)%2];
    }
  }

  // Result will be send to cout                                                
  std::cout << "Fibonacci[" << fn << "] is " << buffer[(fn-1)%2] << std::endl;
  return EXIT_SUCCESS;
}
于 2013-12-26T21:04:18.703 回答
2

斐波那契数列是 {0, 1, 1, 2, 3, ... N - 1, N, 2N - 1}。

为了实现它,您需要有一个N - 2变量和一个N - 1变量,以便您可以计算N = (N - 2) + (N - 1)

unsigned int count = 0;
std::cin >> count;
// assume count >= 2
unsigned int prev2 = 0;
unsigned int prev1 = 1;

std::cout << prev2 << " " << prev1 << " ";
for (unsigned int i = 2; i < count; ++i)
{
    unsigned int current = prev2 + prev1;
    prev2 = prev1;
    std::cout << current << " ";
    prev1 = current; 
}
std::cout << std::endl;
于 2013-11-01T00:07:45.480 回答
1
#include<iostream.h>
#include<conio.h>

void main()
{ 
   clrscr();
   int arr[50],n,i;
   cout<<"Enter the no. of elements to be printed in fibonacci series : ";
   cin>>n;
   arr[0]=0;arr[1]=1;
   for(i=2;i<n;i++)
   { 
      arr[i]=arr[i-1]+arr[i-2];         
   }
   cout<<"\nThe fibonacii series is : "<<endl;
   for(i=0;i<n;i++)
   {
      cout<<arr[i]<<"\t";  
   }
   getch();
}
于 2013-12-22T08:57:38.460 回答
1
#include <iostream>
using std::cout; using std::cin;

int main()
{
    unsigned int a=0u, b=1u, n;//assuming n is a positive number.
                                //otherwise make it int instead of unsigned
                                //and check if it's negative
    cin >> n;

    if(n==0)
       {return 0;}
    if(n==1)
       {cout << a; return 0;}
    cout << a << " " << b << " ";
    for(unsigned int i=2u ; i<n; i++)
    {
       b = a + b;
       a = b - a;
       cout << b << " ";
    }
    return 0;
}

它通过将最后两个值加在一起将下一个值放入“b”中。'a' 然后获取前一个 b 值。假设 a = 3 和 b = 5。那么新的 b 将变为 8,而 'a' 将变为 5。这是因为它总是将最后两个数字相加得到下一个数字的结果。下一个操作将求和 5(当前 a)和 8(当前 b)等等......

于 2013-11-01T00:34:41.607 回答
1

堆栈溢出当然是递归版本的限制。如果这不是问题,您可能还希望考虑递归斐波那契的模板版本。

#include <iostream>

template <int N> int Fib(){ return Fib<N-1>() + Fib<N-2>(); }
template <> int Fib<1>() { return 1; }
template <> int Fib<0>() { return 1; }

using namespace std;
int main()
{
  // For the 10th Fibbonacci number...
  cout << Fib<10>() << endl;
  return 0;
}
于 2018-05-23T07:47:44.680 回答
0
#include <iostream>

using namespace std;

int main()

{

    int num1 = 0, num2 = 1 , num_next = 1, n;

        cout << "enter a number: \n";
        cin >> n;
        //for when a negative value is given
        while(n < 0)
        {
            cout << "ERROR\n";
            cin >> n;
         }
         //when any positive number (above 1 is given)
        if (n > 0)
        {
            //to give the value of 0 without ruining the loop
            cout << num1 << " ";
            for (int i = 0; i < n; i++)
            {
                //the Fibonacci loop
                cout << num_next << " ";
                num_next = num1 + num2;
                num1 = num2;
                num2 = num_next;
            }
        }
        //for when 0 is the given value
        else if (n == 0)
            cout << n << " ";
    return 0;
}
于 2014-11-16T09:43:31.613 回答
0

好吧,我一直在寻找一些递归解决方案来完成相同的任务,大多数人所做的是,他们编写一个递归函数来查找第 n 个斐波那契数,然后在主程序中,他们运行一个循环 n 次,并调用这个递归使用值 1 到 n 的函数来获取所有 n 个斐波那契数并打印它们,这是一个很大的开销。

这是一个执行相同任务的解决方案,但它只调用一次递归函数来获取最多 n 个斐波那契数,并将它们存储在一个数组中,然后打印。这比我前面提到的要快 ((n-1)*(recursive call's overhead)) 倍。如果您觉得有帮助,请竖起大拇指:)

#include<iostream>
using namespace std;
int *arr;
int iter = 0;
int len;
int returnValue;
void exist(int num, int arr[] ) /* this function checks if the Fibonacci number that recursive function have calcuated is already in the array or not, mean if it is already calculated by some other recursive call*/
{
    bool checkExistance = false; /* if this is true, means this Fibonacci number is already calculated and saved in array, so do not save it again*/
    returnValue = num;
    for (int i = 0; i< len; i++)
    {
        if(arr[i]==num)
        {
            checkExistance = true;
            break;
        }
    }
    if(!checkExistance)
    {
        arr[iter]=num;
        iter++;
    }
}
int fibonacci(int n)
{   
    if (n==1)
    {
        exist(1,arr);
        return 1;
    }   
    else if (n==2)
    {
        exist(1,arr);
        return 1;
    }
    else
    {
        exist((fibonacci(n-1)+fibonacci(n-2)),arr);
        return returnValue;
    }
}
int main()
{
    int n;
    cout<<"Enter the number of Fibonacci you want to print: ";
    cin>>n;
    len = n;
    arr = new int[n];
    fibonacci(n);
    arr[n-1] = 1;
    cout<<"1:\t"<<arr[n-1]<<endl;
    for (int i = 0; i< len-1; i++)
    {
        cout<<i+2<<":\t"<<arr[i]<<endl;
    }
    return 0;
}
于 2014-04-20T19:50:50.750 回答
0

这是一个没有临时变量的解决方案:

#include <iostream>
using namespace std;

int main()
{
  int n0 = 0;
  int n1 = 1;
  int n;

  cout << "Prints first N in Fibonacci series. Please enter a number for N:  ";
  cin >> n;

  for(int i = 0; i < n; i++) {
    cout << n0 << " ";
    n1 = n0 + n1;
    n0 = n1 - n0;
  }
}

也是一个(尾)递归解决方案:

#include <iostream>
using namespace std;

void fib(int n, int n0, int n1) {
 if(n <= 0) {
    return;
  } else {
    cout << n0 << " ";
    fib(n-1, n1, n0 + n1);
  }
}

int main()
{
  int n;

  cout << "Prints first N in Fibonacci series. Please enter a number for N: ";
  cin >> n;

  fib(n, 0, 1);
}
于 2014-11-21T20:34:38.053 回答
0
/* Author: Eric Gitangu
   Date: 07/29/2015
   This program spits out the fibionacci sequence for the range of 32-bit numbers
   Assumption: all values are +ve ; unsigned int works here
*/
#include <iostream>
#include <math.h>
#define N pow(2.0,31.0)

using namespace std;

void fibionacci(unsigned int &fib, unsigned int &prevfib){
    int temp = prevfib;
    prevfib = fib;
    fib += temp;
}
void main(){
    int count = 0;
    unsigned int fib = 0u, prev = 1u;

    while(fib < N){
        if( fib ==0 ){
            fib = 0;
            cout<<" "<< fib++ <<" \n ";
            continue;
        }
        if( fib == 1 && count++ < 2 ){
            fib = 1;
            cout<< fib <<" \n ";
            continue;
        }
        fibionacci(fib, prev);
        cout<< fib <<" \n ";
    }
}
于 2015-07-30T09:32:09.213 回答
0

再来看看递归解决方案怎么样:

void fibonacci(int n1, int n2, int numCount)
{
  --numCount;

  if (numCount > 0)
  {
    cout << n1 << ", ";
    fibonacci(n2, n1 + n2, numCount);
  }
  else
    cout << n1 << endl;
}

然后你可以称之为:

enterint fNum;
cout << "Enter a non negative number to print output fibonacci sequence: ";
cin >> fNum;

fibonacci(0, 1, fNum);

输出示例:

斐波那契示例输出

于 2017-10-27T09:31:22.273 回答
0

您可以编写一个生成斐波那契数列的代码,避免打印零和一的 if-else 语句,避免在循环外打印它们并避免使用“temp”整数。您可以通过使用 -1 和 1 初始化“第一”和“第二”变量来做到这一点,因此它们之间的总和将为您提供 0,这是该系列的第一个器官,而循环将完成其余的工作.

#include <iostream>

using namespace std;
int main()
{
    int num, a = -1, b = 1; 
    cout << "enter a number:" << endl;
    cin >> num;
    for (int i = 0 ; i <= num ; i++ ) 
    {
    b += a;             
    cout << b << " "; 
    a = b - a;
    }
    cout << endl;
    return 0;
}
于 2019-11-21T23:15:30.663 回答
0

简洁版:

int n, a{0}, b{1};
std::cin >> n;
while (n-- > 0) {
    std::cout << a << " ";
    std::tie(a, b) = std::make_tuple(b, a + b);
}
于 2019-10-07T16:58:05.580 回答
0

所以......这是“如果你想要 Fib 的特定序列”的解决方案。

#include <iostream>
using namespace std;
int fibonacciSeq(int k)
{
    int num1=1;
    int num2=1;
    int count;
    for(int i=0; i<k; i++)
    {
        if(i==1)
        count=1;
        else
        {
            count=num1+num2;
            num1=num2;
            num2=count;
        }
    }
    return count;
}
于 2015-11-17T02:23:09.963 回答