给我一个用C++写的汉诺塔问题的代码
时间: 2023-05-12 20:05:07 浏览: 69
以下是用C语言实现汉诺塔问题的代码:
```c
#include <stdio.h>
void hanoi(int n, char A, char B, char C) {
if (n == 1) {
printf("%c -> %c\n", A, C);
} else {
hanoi(n - 1, A, C, B);
printf("%c -> %c\n", A, C);
hanoi(n - 1, B, A, C);
}
}
int main() {
int n;
printf("请输入汉诺塔的层数:");
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}
```
这个程序可以让用户输入汉诺塔的层数,然后输出每一步的移动过程。
相关问题
用c++写一下汉诺塔问题
好的,以下是用C++实现汉诺塔问题的代码:
```c++
#include <iostream>
using namespace std;
void hanoi(int n, char a, char b, char c) {
if (n == 1) {
cout << a << " -> " << c << endl;
return;
}
hanoi(n - 1, a, c, b);
cout << a << " -> " << c << endl;
hanoi(n - 1, b, a, c);
}
int main() {
int n; // 汉诺塔层数
cout << "请输入汉诺塔的层数:";
cin >> n;
hanoi(n, 'A', 'B', 'C');
return 0;
}
```
在这个代码中,我们定义了一个 `hanoi` 函数,它的参数 `n` 表示汉诺塔的层数,`a`、`b`、`c` 分别表示三个柱子的名称。在 `n` 等于 1 的时候,我们直接将第一个柱子上的盘子移动到第三个柱子上;否则,我们将 `n-1` 层的盘子从第一个柱子移动到第二个柱子上,再将第 `n` 层的盘子从第一个柱子移动到第三个柱子上,最后再将 `n-1` 层的盘子从第二个柱子移动到第三个柱子上,这样就完成了整个移动过程。
在 `main` 函数中,我们先让用户输入汉诺塔的层数,然后调用 `hanoi` 函数进行移动。
用c++写一段汉诺塔代码
#include<stdio.h>void hanoi(int n, char source, char dest, char aux){
if (n == 1){
printf("从 %c 移动盘子 %d 到 %c\n", source, n, dest);
return;
} hanoi(n-1, source, aux, dest);
printf("从 %c 移动盘子 %d 到 %c\n", source, n, dest);
hanoi(n-1, aux, dest, source);
}int main(){
int n;
printf("输入盘子数量: ");
scanf("%d", &n);
hanoi(n, 'A', 'C', 'B');
return 0;
}
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)