Онлайн компилятор C

#include <stdio.h> void hanoi(int n, int from, int to, int temp){ if(n==1){ printf("%d %d %d\n",temp,from,to); return; } hanoi(n-1, from, to, temp); printf("%d %d %d/n",temp,from,to); hanoi(n-1, to,from,temp); } int main() { int x; scanf("%d",&x); hanoi(x); return 0; }
这段代码试图实现汉诺塔问题的递归解法,但存在几个问题。

首先,`hanoi`函数被定义了4个参数,但在`main`中调用时只传入了1个参数`x`,这会导致编译错误。其次,递归逻辑和输出格式也有问题。

- 在`main`中调用`hanoi(x)`时,需要传入正确的4个参数,比如`hanoi(x, 1, 3, 2)`,分别代表盘子数、起始柱、目标柱和辅助柱。
- 递归函数内部,当`n==1`时,应该直接输出从`from`到`to`的移动,而不是输出`temp`。当前输出语句中使用了`temp`,这是错误的。
- 递归调用时,参数顺序需要正确:先将`n-1`个盘子从`from`移到`temp`(借助`to`),然后移动第`n`个盘子,最后将`n-1`个盘子从`temp`移到`to`(借助`from`)。当前递归调用的参数顺序有误。
- 输出格式中的`/n`应该是`\n`,否则不会换行。