Finding the average number of guesses
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Write a program, ImprovingGuessing.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.
This is what I have for the code, but I am stuck on how to find the average number of guesses. Any help would be appreciated. Thank you.
right=randi(20);
disp('I am thinking of a number between 1 and 20')
Number_of_guesses= 0;
guess=0 ;
while (guess~= right)
b=input ('Do you want to guess again? q for NO, 1 for YES');
if b==0;
break;
else
Number_of_guesses=Number_of_guesses +1;
guess= input('Guess the number:\n');
if guess> right
fprintf('Too high\n')
elseif guess< right
fprintf('Too low\n', guess);
else
fprintf('You guessed it! Congrats!\n', right)
fprintf ('It took you %d guesses to get it correct\n', Number_of_guesses)
end
end
end
0 Commenti
Risposte (1)
Jan
il 27 Mar 2019
In the lines:
fprintf('Too low\n', guess);
and
fprintf('You guessed it! Congrats!\n', right)
there is an argument, but no corresponding format string. Omit the trailing argument.
All you need is an additional loop:
ready = false;
nLoop = 0;
nAnswer = 0;
while ~ready
... Your code
nLoop = nLoop + 1;
nAnswer = nAnswer + Number_of_guesses;
s = input('Type ''q'' if you want to quit...', 's');
ready = strcmpi(s, 'q');
end
Now you have the number of answers and the number of loop. This is sufficient to get the average number of answers.
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!