Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 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;

Weitere Antworten (1)

David Hill
David Hill am 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);

Kategorien

Mehr zu Video games finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by