Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Modify the guessing program of Listing 8.4 so that it uses a more intelligent guessing strategy.
- For example, have the program initially guess 50, and have it ask the user whether the guess is high, low, or correct.
- If, say, the guess is low, have the next guess be halfway between 50 and 100, that is, 75.
- If that guess is high, let the next guess be halfway between 75 and 50, and so on. Using this binary search strategy,
- the program quickly zeros in on the correct answer, at least if the user does not cheat.
- */
- #include <stdio.h>
- int main(void)
- {
- const int MIN = 1, MAX = 100;
- int calc_guess = 50, num_of_guess = 1, guess = 50;
- int diff_resp = 1;
- char choice;
- printf("Think of a number, 1-100, and I'll guess what it is.\nJust let me know if I'm too high or too low.\n");
- printf("When you have thought of your number, hit enter.\n");
- while (getchar() != '\n')
- continue;
- printf("\nMy first guess is 50.\n");
- printf("Enter the letter that represents your choice.\n\n");
- printf("a) Too High b) Too Low c) Correct\n");
- while ((choice = getchar()) != 'c') {
- //Input Validation
- if (choice == '\n')
- continue;
- if ((choice != 'a') && (choice != 'b')) {
- printf("\nPlease enter a valid option.\n");
- printf("a) Too High b) Too Low c) Correct\n");
- continue;
- }
- //Approximation Algorithm
- if (num_of_guess < 4) {
- if (choice == 'a')
- guess -= calc_guess / (num_of_guess * 2);
- if (choice == 'b')
- guess += calc_guess / (num_of_guess * 2);
- ++num_of_guess;
- }
- //Fine tune to answer
- else {
- if (choice == 'a')
- --guess;
- else
- ++guess;
- }
- //Boundary Enforcer
- if (guess < MIN)
- guess = MIN;
- if (guess > MAX)
- guess = MAX;
- //Response Variety
- if (diff_resp == 1)
- printf("\nFine, but what about %d?\n", guess);
- else
- printf("\nWell then, is it %d?\n", guess);
- printf("a) Too High b) Too Low c) Correct\n");
- diff_resp = -diff_resp;
- }
- printf("\nHurray! I WIN! HAHAHAHA YOU LOSE! LOSER.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement