# 小專題1 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> void guessGame(void); // function prototype int isCorrect(int, int); // function prototype int main(void) { // srand( time( 0 ) ); // seed random number generator guessGame(); } // end main // guessGame generates numbers between 1 and 1000 // and checks pc's guess **void guessGame(void) { int answer; // randomly generated number int pcguess; // pc's guess int response = 1; // 1 or 2 response to continue game int frequency; //record guess frequency; // generate random number between 1 and 1000 // 1 is shift, 1000 is scaling factor answer = 1 + rand() % 1000; pcguess = 1 + rand() % 1000; // loop until correct number while (1) { int max = 1000,min = 1; if(isCorrect(pcguess, answer) == 3){ break; } if(isCorrect(pcguess, answer) == 2){ max = pcguess ; pcguess = min + rand() % max; frequency ++; } if(isCorrect(pcguess, answer) == 1){ min = pcguess ; pcguess = min + rand() % max; frequency ++; } } printf("88 88 \n"); printf("88 "" \n"); printf("88 \n"); printf("88,dPPYba, 88 8b,dPPYba, ,adPPYb,d8 ,adPPYba, \n"); printf("88P' '8a 88 88P' `'8a a8' `Y88 a8' '8a \n"); printf("88 d8 88 88 88 8b 88 8b d8 \n"); printf("88b, ,a8' 88 88 88 '8a, ,d88 '8a, ,a8' \n"); printf("8Y'Ybbd8'' 88 88 88 `'YbbdP'Y8 `'YbbdP'' \n"); printf(" aa, ,88 \n"); printf(" 'Y8bbdP' \n"); printf("guess %d times",frequency); } // end function guessGame** // isCorrect returns 3 if g equals a // if g does not equal a, displays hint int isCorrect(int g, int a) { printf("%d\n",g); // guess is correct if (g == a){ return 3; } // guess is incorrect; display hint else if (g < a) { printf( "%s", "Too low. Try again.\n " ); return 1; } else { printf( "%s", "Too high. Try again.\n " ); return 2; } return 0; } ``` 實作的方法是二分法 首先讓電腦生成亂數用來當作答案變數命名為answer 生成一個亂數當作答案變數命名為pcguess 設定一個變數為猜測的次數 寫一個函式用來判斷pcguess是否正確 並且給電腦指示往上猜還是往下 寫一個函式用來執行猜測 猜測方法是二分法 首先設定二分法的最大與最小值 接著使用while迴圈來執行猜測 使用if來判斷猜測(判斷式可以用剛剛寫的函式) 正確的值是3就break掉迴圈 不是的話繼續執行下個if 如果猜測的值等於2讓最大值等於pcguess 接下來讓pcguess重新生成最小到之前pcguess的值 然後猜測次數增加 不是的話繼續執行下個if 如果猜測的值等於1讓最小值等於pcguess 接下來讓pcguess重新生成最大到之前pcguess的值 然後猜測次數增加 跳出迴圈後印出bingo的ASCII CODE 接著印出猜測的次數。