gpt4 book ai didi

c++ - 将迭代函数转换为递归函数

转载 作者:行者123 更新时间:2023-11-30 05:47:56 25 4
gpt4 key购买 nike

我正在与同事讨论如何将以下迭代函数转换为严格递归函数。我们知道,所有的迭代函数都可以转化为递归函数;然而,我的同事记得这个特定的实现只使用了三个参数。我们无法重新解决此问题。我们是不是记错了?还是我们遗漏了一些简单的东西?

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 你可以在 here 中看到, 它的输出与代码的输出完全一样 here .

#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 分钟编辑了你的问题,而且我可以看到你自己选择了一条像我的答案一样的路径。

关于c++ - 将迭代函数转换为递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28425976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com