Incorporating guess count into a loop
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Wan Ji
2021-8-15
(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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!