Online Compiler C

#include <stdio.h> void hanoi(int n, int from, int to, int temp){ if(n==1){ printf("%d %d %d\n",n,from,to); return; } hanoi(n-1, to,from,temp); printf("%d %d %d\n",n,from,to); hanoi(n-1, from,to,temp); } int main() { int x; scanf("%d",&x); hanoi(x,3,2,3); return 0; }
这段代码试图实现汉诺塔问题的递归解法,但存在逻辑错误。函数 `hanoi` 的目标是将 `n` 个盘子从 `from` 柱移动到 `to` 柱,借助 `temp` 柱。代码中递归调用的参数顺序不正确,导致移动步骤出错。

- 在 `hanoi(n-1, to, from, temp)` 这一行,参数顺序应该是 `hanoi(n-1, from, temp, to)`,因为需要先将上面 n-1 个盘子从 `from` 移到 `temp`,而不是从 `to` 移到 `from`。
- 在 `hanoi(n-1, from, to, temp)` 这一行,参数顺序应该是 `hanoi(n-1, temp, to, from)`,因为需要将 n-1 个盘子从 `temp` 移到 `to`,而不是从 `from` 移到 `to`。
- 另外,`main` 函数中调用 `hanoi(x, 3, 2, 3)` 的初始参数可能不符合预期,通常第一个参数是起始柱,第二个是目标柱,第三个是辅助柱。检查一下你希望从哪个柱子开始,移动到哪个柱子。