gpt4 book ai didi

c++ - 为什么递归向后工作?

转载 作者:搜寻专家 更新时间:2023-10-31 00:06:29 24 4
gpt4 key购买 nike

我无法理解这种递归的工作原理。为什么输出显示:C B A 而不是 A B C?

void recur(const char* sth) {

if (*sth != 'D') {
recur(sth+1);
std::cout << *sth << std::endl;
}
}

int main(){

recur("ABCD");
}

一开始,我有'ABCD',然后我用“BCD”递归调用,但与此同时,递归函数的第一次调用不应该打印“A”吗?

在递归调用中,recur函数要用'CD'再次递归调用,还要第二次调用recur函数print 'B'

等等……

我确信即使函数调用自身,第一次调用也不会自动结束。

我知道你们中的一些人会推荐我使用调试器,但我没有找到任何可以帮助我理解这一点的东西,这就是我决定在这里寻求帮助的原因。

亲切的问候,

最佳答案

第一个元素在所有其他元素之后处理。同样,第二个元素在它之后的所有元素之后处理,依此类推。

void recur(const char* sth) {

if (*sth != 'D') {
recur(sth+1); // <- Here you are processing the rest...
std::cout << *sth << std::endl; // <- ... before processing the current
}
}

尝试翻转这些线。这也使它成为加分的尾递归。


I was convinced that even though function calls itself, the first call doesn't automatically end.

正确,函数必须返回,然后调用方继续。如果没有,那么您将看不到它输出任何内容,因为您是在递归调用之后输出的。

At the start, I've 'ABCD', then I'm calling recursively with 'BCD' but also in the meantime shouldn't the first call of recur function print 'A' ?

它确实“打印”'A'。它在递归调用之后执行,递归调用打印其他所有内容,导致“A”成为最后一个输出。


我看到你说“同时”。递归调用不等待调用者完成或类似的事情。相反,调用者将在递归调用后恢复。需要明确的是,递归调用完成后,调用之后的代码将继续。 使用调试器单步执行代码应该已经清楚了。

关于c++ - 为什么递归向后工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57599809/

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