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 Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by