用c编写以下要求利用递归写一个汉诺塔的游戏。
时间: 2024-05-08 19:15:35 浏览: 86
```
#include <stdio.h>
void hanoi(int n, char A, char B, char C) {
if (n == 1) { // 只有一个盘子时,直接将其从 A 移到 C
printf("Move disk %d from %c to %c\n", n, A, C);
} else {
// 先将 n-1 个盘子从 A 移到 B
hanoi(n-1, A, C, B);
// 将第 n 个盘子从 A 移到 C
printf("Move disk %d from %c to %c\n", n, A, C);
// 最后将 n-1 个盘子从 B 移到 C
hanoi(n-1, B, A, C);
}
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}
```
运行结果:
```
Enter the number of disks: 3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
```
阅读全文