USING MATLAB write the following: Write a program, guessing.m, that does the fol
ID: 2081520 • Letter: U
Question
USING MATLAB write the following:
Write a program, guessing.m, that does the following: The computer generates a random integer between 1 and 20 (inclusive). The computer displays "I am thinking of a number between 1 and 20." It prompts the user to input a guess. While the guess is not equal to the computer's number, it tells the user whether the guess was too low or too high, and prompts for another guess. When the user guesses the right number, the computer congratulates the user and ends the game might look something like this: >> guessing I am thinking of a number between 1 and 20. Enter your guess: 10 Too low Enter your guess: 15 Too high Enter your guess: 13 Right! Write a program, Improving Guessing. m, in which the guessing game automatically repeats over and over until the user quits. Add the ability for the user to quit the program by inputting a "q" or a "0. " At that point, print out the average number of guesses the user needed. In the previous example, the user only needed three guesses. If they have adopted a clever strategy, what is the maximum number of guesses the user should need on average?Explanation / Answer
Guessing.m
function guessing()
clc;
number=round(rand(1)*21);
k=number;
if k==0
number=round(rand(1)*21);
end
fprintf('I am thinking a number between 1 and 20. ');
guess=input('Guess a number: ');
while guess~= number
if guess>number
fprintf('Too high! ');
guess=input('Guess another number: ');
else
fprintf('Too low! ');
guess=input('Guess another number: ');
end
end
fprintf('Right ');
end
ImprovingGuessing.m
function guessing()
clc;
counter=0;
number=round(rand(1)*21);
k=number;
if k==0
number=round(rand(1)*21);
end
fprintf('I am thinking a number between 1 and 20. ');
guess=input('Guess a number: ');
while guess~= number
q=input('Do you want to continue 0 for NO, 1 for yes ');
if q==0
break;
else
counter = counter + 1;
if guess>number
fprintf('Too high! ');
guess=input('Guess another number: ');
else
fprintf('Too low! ');
guess=input('Guess another number: ');
end
end
end
counter=counter+1;
if guess==number
fprintf('Guessed the correct number in %g shots. ', counter);
else
fprintf('number of guesses %g ', counter);
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.