假设有21根火柴棍,两人轮流拿取,每次可以取1-4根,不能多拿,也不能少拿。谁提示:电脑每次拿的火柴棍的数目是5减去你上轮哪的数目 拿最后一根,谁就认输。 实验步骤与要求: (1)你拿的火柴棍数目不在1-4应提示重新拿。 (2)分别用while语句、do-while语句编写程序
时间: 2024-12-11 22:26:49 浏览: 27
这是一个经典的博弈论问题,被称为“汉诺塔”游戏的变种,但是规则稍微有些变化。在这里,我们不需要直接模拟游戏过程,因为实际上计算机可以轻松地计算出最佳策略。不过,我们可以演示如何用while和do-while循环来设计一个简单的游戏模拟程序,尽管它无法自动赢得游戏。
**While循环版本**:
```c
int sticks = 21;
int player = 1; // 假设玩家先手
while (sticks > 0) {
int take;
if (player == 1) { // 玩家选择
take = rand() % 5 + 1; // 玩家随机取1-4根
} else { // 计算机选择
take = 5 - player_last_take; // 计算机按规则取
if (take <= 0 || take > sticks) {
printf("Invalid move! Computer's turn.\n");
continue;
}
}
sticks -= take;
player = 3 - player; // 计算机总是后手,所以每一轮之后玩家改变
player_last_take = take;
if (sticks == 0) {
printf("Player %d wins!\n", player);
break;
}
}
// 在此游戏中添加条件检查并更新player_last_take
```
**Do-while循环版本**:
```c
int sticks = 21;
int player = 1;
int player_last_take = 0;
do {
if (player == 1) {
int take = rand() % 5 + 1;
if (take <= 0 || take > sticks) {
printf("Invalid move! Player %d's turn.\n", player);
} else {
sticks -= take;
}
} else {
int take = 5 - player_last_take;
if (take <= 0 || take > sticks) {
printf("Invalid move! Computer's turn.\n");
} else {
sticks -= take;
player_last_take = take;
}
}
player = 3 - player; // 计算机总是后手
} while (sticks > 0);
if (sticks == 0) {
printf("Player %d wins!\n", player);
}
```
阅读全文