问题
I just started learning c++ by myself. I am trying to practice recusion now. I want to print all n(input by user) fibonacci numbers using recursion, but it does not work. Could you help me? Thank you!!
#include <iostream>
using namespace std;
int fibonacci(int n)
{
if (n==1)
{
return 1;
cout<<1<<" ";
}
else if (n==2)
{
return 1;
cout<<1<<" ";
}
else
{
return (fibonacci(n-1)+fibonacci(n-2));
cout<<fibonacci(n-1)+fibonacci(n-2)<<" ";
}
}
int main()
{
int n;
cin>>n;
fibonacci(n);
return 0;
}
回答1:
If you look at Rosetta Code page for Fibonacci, you see that F(0) == 0
and F(1) == 1
.
int fibonacci(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1) + fibonacci(n-2);
}
return fib;
}
In this case, you have a function that will calculate the fibonacci number at a specific position, right?
So now you need to calculate them and then print them:
int main()
{
int n;
cin >> n;
if (n < 0)
{
return -1; // This means there was an error
}
for (int i = 1; i < n; ++i)
{
cout << fibonacci(i) << " ";
}
return 0;
}
Note that this is not the most efficient way to do it at all, but it kinda helps you understand how recursion works.
回答2:
No need for cout in Fibonacci function, only cout by loop in int main()... also change IF condition in Fibonacci function to <=0 otherwise it will give you a segmentation fault (error)
#include <iostream>
using namespace std;
int fibonacci(int n)
{
if (n<=0)
{
return 0;
// cout<<1<<" ";
}
else if (n==1)
{
return 1;
// cout<<1<<" ";
}
else
{
return (fibonacci(n-1)+fibonacci(n-2));
// cout<<fibonacci(n-1)+fibonacci(n-2)<<" ";
}
}
int main()
{
int n;
cin>>n;
for (int x = 0; x < n; x++)
cout << fibonacci(x) << " ";
cout << endl;
return 0;
}
回答3:
Even if you place cout
before your return statement, your code will not give you the fibonacci series in the right order. Let's say you ask for fibonacci(7)
. It will print all the intermediate computations for fibonacci(6)
, and then it will print all 1's for fibonacci(5)
.
来源:https://stackoverflow.com/questions/21781247/printing-fibonacci-series-using-recursion-in-c