Incorporating guess count into a loop
3 views (last 30 days)
Show older comments
Hi all
I am currently trying to get a guess counter into a loop i have, i am unsure as to where it goes. I understand how to do it i think but not sure how to implement it.
This is my current code but again not sure how to implement my guess counter, it is down the bottom and i get an error.
y=randi(100);
while (1)
prompt= '\nguess a value between 1 and 100: ';
x=input(prompt);
if (x<y)
disp('guess higher');
elseif (x>y)
disp('guess lower');
else
disp('you win');
break.
end
guesses = 0;
value = 1;
while( true )
guess = guesses + 1;
end
end
0 Comments
Answers (1)
Wan Ji
on 15 Aug 2021
(1) guess higher and guess lower were in the wrong position;
(2) the count guessTimes should be initialized outside of the loop
(3) Every prompt will increase the guessTimes by 1.
y=randi(100);
guessTimes = 0;
while (1)
prompt= '\nguess a value between 1 and 100: ';
x=input(prompt);
guessTimes = guessTimes + 1;
disp(x)
if (x<y)
disp('guess lower');
elseif (x>y)
disp('guess higher');
else
disp('you win');
fprintf('guess times:%d\n',guessTimes);
break;
end
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!