#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char *choices[] = {"石头", "剪刀", "布"};
int user_choice, computer_choice;
srand(time(NULL)); // 初始化随机数生成器
printf("选择:0-石头, 1-剪刀, 2-布: ");
scanf("%d", &user_choice); // 获取用户输入
computer_choice = rand() % 3; // 生成0到2之间的随机数作为电脑选择
printf("你选择了: %s\n", choices[user_choice]);
printf("电脑选择了: %s\n", choices[computer_choice]);
// 判断比赛结果
if (user_choice == computer_choice) {
printf("平局!\n");
} else if ((user_choice == 0 && computer_choice == 1) ||
(user_choice == 1 && computer_choice == 2) ||
(user_choice == 2 && computer_choice == 0)) {
printf("你赢了!\n");
} else {
printf("你输了!\n");
}
return 0;
}
说明
- 包含必要的头文件
stdio.h
,stdlib.h
和time.h
。 - 使用
choices
数组存储石头、剪刀和布的字符串表示。 - 初始化随机数生成器
rand()
。 - 获取用户输入并生成电脑随机选择。
- 根据用户和电脑的选择判断并输出比赛结果。