剪刀、石头、布

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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的取值只能是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 (输) 

我认为编此程序 首先分析出 man - computer 的结果可以是1,-2  0  -1,2
其中(man赢的取值是1,-2  平的取值是0,输的取值是-1,2)  利用一些数学表达式运算 把这三类区别开就可以,不一定拘泥在“(man - computer + 4) % 3 - 1”之上。

猜你喜欢

转载自blog.csdn.net/guduyibeizi/article/details/48094375
今日推荐