gpt4 book ai didi

c++ - 需要帮助弄清楚这个 C++ 代码是如何计算的

转载 作者:行者123 更新时间:2023-11-30 05:48:54 27 4
gpt4 key购买 nike

这段代码如何求值?它为我提供了汉诺塔问题的正确解决方案,但我不明白评估的顺序。

void moveDisks(int n, const char* pegA, const char* pegB, const char* pegC)

{
if (n == 0)
{
return;
}

moveDisks(n-1, pegA, pegC, pegB);
std::cout << "Move disk from " << pegA << " to " << pegC << std::endl;
moveDisks(n-1, pegB, pegA, pegC);
}

最佳答案

评论是绝对正确的,但另外这里有一个伪代码/调用堆栈/输出的东西可能有助于概念化它:

moveDisks(4, "A", "B", "C");
moveDisks(3, "A", "C", "B");
moveDisks(2, "A", "B", "C");
moveDisks(1, "A", "C", "B");
Move disk from A to B
Move disk from A to C
moveDisks(1, "B", "A", "C");
Move disk from B to C
Move disk from A to B
moveDisks(2, "C", "A", "B");
moveDisks(1, "C", "B", "A");
Move disk from C to A
Move disk from C to B
moveDisks(1, "A", "C", "B");
Move disk from A to B
Move disk from A to C
moveDisks(3, "B", "A", "C");
moveDisks(2, "B", "C", "A");
moveDisks(1, "B", "A", "C");
Move disk from B to C
Move disk from B to A
moveDisks(1, "C", "B", "A");
Move disk from C to A
Move disk from B to C
moveDisks(2, "A", "B", "C");
moveDisks(1, "A", "C", "B");
Move disk from A to B
Move disk from A to C
moveDisks(1, "B", "A", "C");
Move disk from B to C

如果您阅读有关递归的内容或像评论建议的那样开始使用调试器(您应该这样做!),您会经常看到这样的图表。

关于c++ - 需要帮助弄清楚这个 C++ 代码是如何计算的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28015082/

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