Write a “Guess My Number Game” program. The program
generates a random integer in a specified range, and the user (the
player) has to guess the number. The program allows the use to play
as many times as he/she would like; at the conclusion of each game,
the program asks whether the player wants to play again.
The basic algorithm is:
1. The program starts by printing instructions on the screen.
2. For every game:
the program generates a new random integer in the range from MIN
to MAX. Treat MIN and MAX like constants; start by initializing them
to 1 and 100
loop to prompt the player for a guess until the player correctly
guesses the integer
for each guess, the program prints whether the player’s guess
was too low, too high, or correct
at the conclusion (when the integer has been guessed):
print the total number of guesses for that game
print a message regarding how well the player did in that
game (e.g the player took way too long to guess the number,
the player was awesome, etc.). To do this, you will have to
decide on ranges for your messages and give a rationale for
your decision in a comment in the program.
3. After all games have been played, print a summary showing the
average number of guesses.
Ch5Ex41.m
% Guess My Number Game
disp('This is a Guess My Number Game!')
disp('I will pick a random integer; see if you can guess it')
MIN = 1;
MAX = 100;
playagain = true;
tot_no_guesses = 0;
count_games = 0;
while playagain
count_games = count_games + 1;
guesses = 1;
randomint = randi([MIN, MAX]);
yourint = input('Enter your guess: ');
while randomint ~= yourint
if yourint < randomint
disp('Too low')
yourint = input('Enter your guess: ');
guesses = guesses + 1;
elseif yourint > randomint
disp('Too high')
yourint = input('Enter your guess: ');
guesses = guesses + 1;
else
disp('Correct!')
end
end
fprintf('It took you %d guesses, which is ', guesses)
if guesses < 5
fprintf(' awesome\n')
elseif guesses > 10
fprintf(' pretty weak\n')
else
fprintf(' OK\n')
end
tot_no_guesses = tot_no_guesses + guesses;
playagain = upper(input('Play again? ', 's')) == 'Y';
end
fprintf('The ave # of guesses was %.2f\n',
tot_no_guesses/count_games)
need an explanation for this answer? contact us directly to get an explanation for this answer