Clear Filters
Clear Filters

Is it possible to record the final value of each while loop?

2 views (last 30 days)
I'm a beginner for MatLab and I cannot figure out how to find the mean of the final values for a while loop. I am currently working on a small game where the program generates a random number and the user has to guess what it is. The number of guesses is recorded and at the end of each game the user is asked if they want to play again or not. If the user says no then the average number of guesses is displayed. My problem is that I can't seem to figure out if there is a way to save the total number of guesses for each game, save it, and then find the average to be displayed. Any help would be great! Thank you.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Feb 2022
Before the first while
total_guesses = 0;
games_played = 0;
Then just before the last end of that while loop:
total_guess = total_guesses + rounds;
games_played = games_played + 1;
and after the loop,
m = total_guesss ./ games_played;

More Answers (1)

David Hill
David Hill on 8 Feb 2022
play='y';
count=0;
while isequal(play,'y')
guess=0;
count=count+1;
rounds(count)=1;
number=randi(100);
while ~isequal(guess,number)
guess=input('Please enter your guess: ');
if guess > number
fprintf('High \n');
elseif guess < number
fprintf('Low \n');
else
break;
end
rounds(count)=rounds(count)+1;
end
if rounds < 10
fprintf('You are a genius! It only took you %d guesses. \n',rounds);
else
fprintf('You need to work on your guessing skills! It took you %d guesses. \n',rounds);
end
play = input('Would you like to play again? Please enter ''y'' or ''n'': ','s');
end
m=mean(rounds);
fprintf('The average number of guesses was %.1f \n',m);

Categories

Find more on Video games in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!