c++实现汉诺塔基本解打印,要求能够输入汉诺塔层数(1-10),起始柱(A-C),和目标柱(A-C)。同时对每个解前方打印编号,每个解一个编号。
时间: 2023-06-15 11:06:55 浏览: 38
以下是c++实现汉诺塔基本解打印的代码,可以满足你的要求:
```c++
#include<iostream>
#include<cstdio>
using namespace std;
int n, count = 0;
void hanoi(int n, char A, char B, char C)
{
if(n == 1)
{
count++;
printf("%d: Move disk %d from %c to %c\n", count, n, A, C);
}
else
{
hanoi(n-1, A, C, B);
count++;
printf("%d: Move disk %d from %c to %c\n", count, n, A, C);
hanoi(n-1, B, A, C);
}
}
int main()
{
char start, end;
printf("Please enter the number of layers (1-10): ");
scanf("%d", &n);
printf("Please enter the start column (A-C): ");
cin >> start;
printf("Please enter the target column (A-C): ");
cin >> end;
hanoi(n, start, 'B', end);
return 0;
}
```
注意,这里的起始柱和目标柱只能输入 A、B、C 中的一个。如果需要增加输入判断,可以在程序中加入相应的语句。