递归实现斐波那契数列:如何按目标格式输出序列项?
调整斐波那契递归程序的输出格式
我看了你的代码,当前程序能运行但存在几个小问题导致输出不够规范:比如最后会多打印一个额外的数值,末尾还有多余的空格,而且递归分支缺少明确的return语句会触发未定义行为。结合常见的数列格式化需求,我帮你调整代码,下面是修改后的版本:
#include <iostream> using namespace std; // 改为void类型,不需要返回值,专注于打印数列 void fibonacci(int count, int num1, int num2); int main() { int n; cout << "Know the Fibonacci Sequence up to the nth term." << '\n'; cout << "Input n: "; cin >> n; // 增加输入合法性判断,避免非正整数输入 if (n <= 0) { cout << "Please enter a positive integer." << endl; return 1; } cout << "The sequence up to fibonacci(" << n << "):" << '\n'; // 直接调用递归函数,不需要用cout接收返回值 fibonacci(n, 0, 1); cout << '\n'; return 0; } void fibonacci(int count, int num1, int num2) { // 打印当前项,仅在非最后一项时添加空格,避免末尾冗余空格 cout << num1; if (count > 1) { cout << " "; } // 递归终止条件:打印完指定数量的项后停止 if (count == 1) { return; } // 递归更新:count减1,前两个数替换为下一组 fibonacci(count - 1, num2, num1 + num2); }
关键改动说明:
- 修改函数返回类型:把
int改成void,原函数的返回值被main额外打印导致多输出一个数,现在只让递归函数负责打印数列项。 - 优化终止逻辑:当
count == 1时停止递归,确保刚好打印n项斐波那契数(比如输入n=5,就输出0、1、1、2、3这5个值)。 - 规范空格输出:只有当不是最后一项时才打印空格,让输出更整洁。
- 增加输入校验:处理用户输入非正整数的情况,让程序更健壮。
如果你的图2需求是每行固定数量的项换行(比如每行5个),可以用下面的版本,新增一个计数器跟踪当前打印的项数,达到指定数量时自动换行:
#include <iostream> using namespace std; // 新增current参数跟踪当前项数,默认值为1 void fibonacci(int count, int num1, int num2, int current = 1); int main() { int n; cout << "Know the Fibonacci Sequence up to the nth term." << '\n'; cout << "Input n: "; cin >> n; if (n <= 0) { cout << "Please enter a positive integer." << endl; return 1; } cout << "The sequence up to fibonacci(" << n << "):" << '\n'; fibonacci(n, 0, 1); cout << '\n'; return 0; } void fibonacci(int count, int num1, int num2, int current) { cout << num1; // 每5个项换一行,同时避免末尾空格 if (count > 1) { cout << " "; if (current % 5 == 0) { cout << '\n'; } } if (count == 1) { return; } fibonacci(count - 1, num2, num1 + num2, current + 1); }
内容的提问来源于stack exchange,提问作者Frazier
相关产品推荐
相关产品推荐

