#include
#include
#include
int main(void)
{
char gesture[3][10] = { "scissor", "stone", "cloth" };
int man, computer, result, ret;
srand(time(NULL));
while (1) {
computer = rand() % 3;
printf("\nInput your gesture (0-scissor 1-stone 2-cloth):\n");
ret = scanf("%d", &man);
if (ret != 1 || man < 0 || man > 2) {
printf("Invalid input! Please input 0, 1 or 2.\n");
continue;
}
printf("Your gesture: %s\tComputer's gesture: %s\n",
gesture[man], gesture[computer]);
result = (man - computer + 4) % 3 - 1;
if (result > 0)
printf("You win!\n");
else if (result == 0)
printf("Draw!\n");
else
printf("You lose!\n");
}
return 0;
}
“(man - computer + 4) % 3 - 1”思路
man 和computer的取值只能是0 1 2,
那么 man - computer 的结果可以是1,-2 0 -1,2 (man赢的取值是1,-2 平的取值是0,输的取值是-1,2)
加上4之后可以是 5,2(赢) 4(平) 3,6(输)
对3进行取余后只有 2(赢) 1(平) 0(输)
再减1 最后只有 1(赢) 0(平) -1 (输)