程式設計-小專題-電子雞自己猜數字
===
我的想法:二分法
===
利用二分法的原理,設定最大值與最小值,然後利用公式(max+min)/2的結果來當作每次猜測的值,範圍在最大值與最小值之間,最後猜出正確答案。
```
// Randomly generate numbers between 1 and 1000 for user to guess.
#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 user's guess
void guessGame(void)
{
int answer; // randomly generated number
int guess; // user's guess
int response; // 1 or 2 response to continue game
int i = 1;
// loop until user types 2 to quit game
do {
int min = 1,max = 1000;
// generate random number between 1 and 1000
// 1 is shift, 1000 is scaling factor
answer = 1 + rand() % 1000;
// prompt for guess
puts("I have a number between 1 and 1000.\n"
"Can you guess my number?\n"
"Please type your first guess.");
printf("%s", "? ");
guess = (min + max) / 2;
printf("%d\n",guess);
// loop until correct number
while (!isCorrect(guess, answer))
{
if (guess < answer)
{
min = guess + 1;
guess = (min + max) / 2;
printf("%d\n",guess);
}
else if (guess > answer)
{
max = guess - 1;
guess = (min + max) / 2;
printf("%d\n",guess);
}
i++;
}
printf("guess %d times\n", i);
// prompt for another game
puts("\nExcellent! You guessed the number!\n"
"Would you like to play again?");
printf(" , , \n");
printf(" /| |\\ \n" );
printf(" / | | \\ \n");
printf(" | | | | \n");
printf(" \\ | | / \n");
printf(" \\|w|/ / \n");
printf(" /_ _\\ / ,\n");
printf(" /\\ _:()_():_ /] \n");
printf(" ||_ : ._=Y=_ : / / \n");
printf(" [)(_\\, ',__\\W/ _,' / \\ \n");
printf(" [) \\_/\\ _/'='\\ /-/\\) \n");
printf(" [_| \\ \\ /// \\ '._ / / \n");
printf(" :; \\ \\/// / | '` / \n");
printf(" ;:: \\ `|: : |',_.' \n" );
printf(" ""' \\_|: : | \n");
printf(" |: : |''. \n");
printf(" /`._.' \\/ \n");
printf(" / /| / \n");
printf(" | \\ / / \n");
printf(" '. '. / \n");
printf(" '. ' \n");
printf(" / \\ \\ \n");
printf(" / / \'=, \n");
printf(" .----' / \\ (\\__ \n");
printf(" snd (((____/ \\ \\ ) \n");
printf(" '.\\_) \n");
printf("%s", "Please type ( 1=yes, 2=no )? ");
scanf("%d", &response);
puts("");
} while (response == 1);
} // end function guessGame
// isCorrect returns true if g equals a
// if g does not equal a, displays hint
int isCorrect(int g, int a)
{
// guess is correct
if (g == a)
return 1;
// guess is incorrect; display hint
if (g < a)
printf( "%s", "Too low. Try again.\n? " );
else
printf( "%s", "Too high. Try again.\n? " );
return 0;
} // end function isCorrect
```