石头剪子布(转自javaeye)
炽翼铁冰
posted @ 2010年5月12日 22:36
in C(转载)
, 2466 阅读
地址如下:http://songjindian.javaeye.com/blog/649805
#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("\n Input your gesture(0-scissor 1-stone 2-cloth):\n"); ret = scanf("%d", &man); if(ret != 1 || man < 0 || man > 2) { printf("Invalid input!\n"); return 1; } printf("Your gesture : %s\tComputers getsture: %s\n", gesture[man], gesture[computer]); result = (man - computer + 4) % 3 - 1; printf("result = %d\n ", result); if( result > 0) printf ("You win!\n"); else if( result == 0 ) printf("Draw!\n"); else printf("You lose!\n"); } return 0; }
分析如下:
人: 0 1 2
电脑:0 1 2
结果: (0-0+4)%3-1=0 (0-1+4)%3-1=-1 (0-2+4)%3-1=1
(1-0+4)%3-1=1 (1-1+4)%3-1=0 (1-2+4)%3-1=-1
(2-0+4)%3-1=-1 (2-1+4)%3-1=1 (2-2+4)%3-1=0