(Guess-the-Number Game Modification) Modify the program of Exercise 6.34 to count the number of guesses the player makes. If the number is 10 or fewer, print "Either you know the secret or you got lucky!"
If the player guesses the number in 10 tries, then print "Ahah! You know the secret!" If the player makes more than 10 guesses, then print "You should be able to do better!" Why should it take no more than 10 guesses? Well, with each “good guess” the player should be able to eliminate half of the numbers. Now show why any number from 1 to 1000 can be guessed in 10 or fewer tries.
Solution:
#include <iostream> using std::cout; using std::cin; using std::endl; #include <cstdlib> #include <ctime> int main() { srand(time(0)); int guess; int number; int counter = 0; char selection = 'y'; while(selection == 'y') { number = rand() % 1000 + 1; //cout << "(Hint: Number is " << number << ")." << endl; //check if program is cheating cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess."; cin >>guess; while(number != guess) { if(number > guess) { counter++; cout << "Too low. Try again." << endl; cin >> guess; } if(number < guess) { counter++; cout << "Too high. Try again." << endl; cin >> guess; } } if(counter < 10) cout << "\nEither you know the secret or you got lucky!"; else if(counter = 10) cout << "\nAhah! You know the secret!"; else cout << "\nYou should be able to do better!"; cout << "Excellent! You guessed the number!\nWould you like to play again (y or n)?"; cin >> selection; } cout << "Thank you!"; return 0; } - or + each time: 500 250 125 63 32 16 8 4 2 1
Post A Comment:
0 comments: