In a set up that provides guesses at a random number: how to get Matlab to display the guess that was correct (e.g. 4th)?

1 view (last 30 days)
I've set up a loop including while, if, and else functions so that five guesses are made before a result is given whether these include the correct or incorrect answer but, in the event of correct, how to get it to display which guess was correct?
  1 Comment
Becky CNS
Becky CNS on 25 Feb 2018
This is the syntax so far : How to change script so it displays correct if answer was included in the 5 guesses but also which guess gave the correct answer?
pickme1_100 = round(100.*rand(1));
Counter = 0;
while Guessedcorrectly ==0 A = input ('enter number between 1 and 100');
Counter = Counter + 1;
if A == pickme1_100 Guessedcorrectly = 1 && Counter == 5;
disp('Correct!');
elseif Guessedcorrectly ==0&& Counter >= 5
disp ('All are wrong, try again!')
end
while Guessedcorrectly ==0
A = input ('enter number between 1 and 100');
Counter = Counter + 1;
if A == pickme1_100
Guessedcorrectly = 1 && Counter == 5;
disp('Correct!');
elseif Guessedcorrectly ==0&& Counter >= 5
disp ('All are wrong, try again!')
end
end
end

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 25 Feb 2018
If you want to guess sequentially, you could have the guess be the index of a for loop.
If you want to guess randomly, you could use a while loop and get the guess by using the randi() function.
Note: guessing will only work if the guesses and correct answer are all integers, otherwise there is virtually no chance you would guess it for a floating point number.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!