Incorporating guess count into a loop

조회 수: 3 (최근 30일)
Ben Hischar
Ben Hischar 2021년 8월 15일
답변: Wan Ji 2021년 8월 15일
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

답변 (1개)

Wan Ji
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by