将迭代函数转换为递归函数
Transform iterative function to recursive function
我和一位同事讨论了如何将下面的迭代函数转换为严格递归函数。我们知道,所有迭代函数都可以转换为递归函数;然而,我的同事记得,这个特定的实现只使用了三个参数。我们无法重新解决这个问题。我们记错了吗?还是我们错过了一些简单的东西?
void iterative_function (char a, char b, int width) {
int i = width;
while (i > 0) {
cout << string(i, a) << string(width-i, b) << endl;
i -= 2;
}
i = width % 2;
while (i <= width) {
cout << string(i, a) << string(width-i, b) << endl;
i += 2;
}
}
当像iterative_function('X', '-', 5)
一样调用时,输出如下所示。
XXXXX
XXX--
X----
XXX--
XXXXX
编辑:以下是递归版本的一个小框架:
void recursive_function (char a, char b, int width) {
if (width > -1) {
cout << string(width, a) << endl;
recursive(a, b, width - 2);
cout << string(width, a) << endl;
}
}
但这里的问题是用连字符填充右边。
这是递归函数,我只是给你的函数添加了另一个len
,你可以在这里看到,它的输出和你代码的输出完全一样。
#include <iostream>
using namespace std;
void i_f(char a, char b, int width,int len) {
if(len <0 || width < 0)
return;
cout <<string(width, a) << string(len, b) << endl;
i_f(a,b,width-2,len+2);
cout <<string(width, a) << string(len, b) << endl;
}
int main() {
i_f('X', '-', 5,0);
return 0;
}
您的代码输出:
XXXXX
XXX--
X----
X----
XXX--
XXXXX
我的代码输出:
XXXXX
XXX--
X----
X----
XXX--
XXXXX
p.S在我发布我的答案后,我看到了你的编辑,尽管你在我回答之前10分钟编辑了你的问题,我可以看到你自己选择了一条与我的答案相似的路径。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- 如何将递归函数(具有两个基本情况)转换为迭代函数
- 将递归函数转换为迭代函数
- 转换递归函数
- Python 3.3 如何将这个递归函数转换为纯收益循环版本?
- 将这个糟糕但功能强大的代码转换为递归函数
- 在turbo c++中,可以将一个普通递归函数转换为尾递归函数来对其进行优化
- 将迭代函数转换为递归函数
- 将迭代函数转换为递归函数
- 如何从递归函数返回指针,该函数将抛光表示法转换为反向抛光表示法
- 递归函数的转换
- 转换递归函数并使其迭代
- 将递归函数转换为尾递归函数
- 将迭代函数转换为递归函数
- C++ |需要帮助从 for 循环函数转换 - >递归函数
- 这个递归函数是如何自动转换成迭代函数的
- 在递归函数中,c++基转换过程中意外输出到屏幕