这就是我的任务:
斐波那契数列(0,1,1,2,3,5,8,13,21,…)从0和1开始,并且具有这样的性质:每个后续的斐波那契数都是前两个斐波那契数的和。
您的任务是使用递归将序列转换为程序,该程序将计算斐波那契数值直到输入整数。
如何获取单个数字并按照图2所示的方式列出它
#include <iostream>
using namespace std;
int fibonacci(int target, int num1, int num2);
int main()
{
int n;
cout << "Know the Fibonacci Sequence up to the nth
term." ;
cout << '\n';
cout << "Input n: ";
cin >> n;
cout << "The sequence up to fibonacci(" << n <<"):";
cout << '\n';
cout << fibonacci(n-1,0,1);
cout << '\n';
return 0;
}
int fibonacci(int target, int num1, int num2)
{
cout << num1 << " ";
if(target == 0)
{
return num1 + num2;
}
else {
fibonacci(target-1, num2, num1 + num2);
}
}
现在我的程序就是这样运行的
这是我的目标
发布于 2020-12-09 16:42:22
当您到达n = 0
时,您将返回下一个斐波纳契数,因为您的加法:
if(target == 0)
{
// here you have:
// num1 = 34
// num2 = 55
return num1 + num2;
}
要修复它,只需返回num2
即可。
https://stackoverflow.com/questions/65212909
复制相似问题