簡單的猜數字游戲!
/* 最經典的猜數字游戲的例子來展示條件結構在程序中的作用,今天看到另外一種猜數字的玩法,也挺有趣: 這個游戲由三個人一起玩, 一個人做主持人,心中默想一個1到100之間的數字,然后由其他兩個人輪流猜,每次猜測之后,主持人就說出猜測的這個數比他心中 的數字是大還是小,然后另外一個人根據這個信息繼續猜測,如此輪流,最后誰猜中就算誰輸了。(算贏了也可以) 這是一個相互挖坑 讓對方跳的過程,特別是最后幾步,猜測范圍越來越小,真是步步驚心,稍不留意,就踩到對方挖的坑里去了。 ============================================================================ Name : numbergame1.c Author : lixiaolong Version : v1.0 Copyright : Your copyright notice Description : number of game in C, Ansi-style Encoding time:2013年10月31日11:09:41 ============================================================================ */ #include <stdio.h> #include <time.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> int main() { srand( time(NULL) );//隨機數種子 while(true) { int min = 1; int max = 100;//初始范圍 int count = 0;//猜測次數 const int target = rand()%max + 1;//產生隨機數的目標數 while(true) { int guess = 0; printf("please input a number between %d and %d\n",min,max); fflush(stdin);//清空輸入緩存,以便不影響后面輸入的數。比如你逐個輸入字符,他幫你緩沖掉你每輸入一個字符后面所敲的回車鍵。否則回車也會被當成字符保存進去。 scanf("%d",&guess); // 獲取猜測的數字 ++count; if(guess < min || guess > max) //超出范圍 { printf("the input is out of %d - %d\n",min,max); continue; } else { if(target == guess) //猜中 { printf("YOU WIN!\nyou have guessed %d times in total.\n",count); break; } else if(target > guess) //目標比猜的數字大 { min = guess; printf("the target is larger than %d\n",guess); } else //目標比猜的數字小 { max = guess; printf("the target is less than %d\n",guess); } } } //本輪游戲結束,是否繼續 printf("Do you want to play again?(Y - yes,N - no)\n"); fflush(stdin); char c = 'Y'; scanf("%c",&c); if(toupper(c) != 'Y') { break; } } return 0; }
這個程序扮演了主持人出數字並進行判斷的角色,可以和朋友(女朋友更合適)兩個人一起玩,也可以一個人玩,看看那次猜測的次數最少。