1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 int main(void) 5 { 6 char gesture[3][10] = { "scissor", "stone", "cloth" }; 7 int man, computer, result; 8 srand(time(NULL)); 9 int ret; 10 while (1) { 11 computer = rand() % 3; 12 printf("\nInput your gesture (0-scissor 1-stone 2-cloth):\n"); 13 scanf("%d",&man); 14 if ( man < 0 || man > 2) { 15 fflush(stdin); 16 printf("Invalid input! Please input 0, 1 or 2.\n"); 17 continue; 18 } 19 printf("Your gesture: %s\tComputer's gesture: %s\n", gesture[man], gesture[computer]); 20 result = (man - computer + 4) % 3 - 1; 21 if (result > 0) 22 printf("You win!\n"); 23 else if (result == 0) 24 printf("Draw!\n"); 25 else 26 printf("You lose!\n"); 27 } 28 return 0; 29 } |
原帖由 OwnWaterloo 于 2009-5-23 07:50 发表
估计回帖的人都没看这句话。
注意检查scanf的返回值。
如果输入错误, scanf并不会将不符合格式需要的字符(比如对于整数,'z'就是)从流中取走。
而是将其保留在原处,下一次输入是仍然从这个'z'开始 ...
欢迎光临 Chinaunix (http://bbs.chinaunix.net/) | Powered by Discuz! X3.2 |