C语言石头剪刀布小游戏:完整代码和解析
下面是一个用C语言编写的石头剪刀布小游戏的代码,并附带详细的解释:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int player, computer, result;
srand(time(NULL)); // 初始化随机数种子
printf("欢迎来玩石头剪刀布游戏!\n");
printf("1. 石头\n2. 剪刀\n3. 布\n");
printf("请选择你的出拳:");
scanf("%d", &player);
computer = rand() % 3 + 1; // 计算电脑出拳
// 判断输赢
if (player == computer) {
result = 0;
} else if (player == 1 && computer == 2 || player == 2 && computer == 3 || player == 3 && computer == 1) {
result = 1;
} else {
result = -1;
}
// 输出结果
if (result == 0) {
printf("平局!\n");
} else if (result == 1) {
printf("你赢了!\n");
} else {
printf("你输了!\n");
}
return 0;
}
程序的运行步骤如下:
-
初始化随机数种子: 使用
srand(time(NULL))初始化随机数种子,确保每次运行程序时电脑出拳都是随机的。 -
玩家输入出拳: 程序提示玩家输入 1(石头)、2(剪刀)、3(布)来选择出拳。
-
电脑随机出拳: 使用
rand() % 3 + 1生成 1 到 3 的随机数,代表电脑的出拳。 -
判断输赢: 使用
if语句判断玩家和电脑的出拳结果,确定谁赢了。 -
输出结果: 根据判断结果输出“平局!”、“你赢了!”或“你输了!”。
本程序简单易懂,可以帮助初学者了解如何使用 C 语言编写简单的游戏程序。
原文地址: https://www.cveoy.top/t/topic/mImg 著作权归作者所有。请勿转载和采集!