I am trying to create a game where a user guesses a number between 1 and 100 using a while loop. But I am getting stuck in an infinite loop. Please help?
39 次查看(过去 30 天)
显示 更早的评论
Here is what I have:
y=randi(1,100)
prompt= 'guess a value between 1 and 100'
x=input(prompt)
while x<y
disp('guess higher')
(strfind(question,checkExit))
end
while x>y
disp('guess lower')
end
while x==y
disp('you win')
end
So, the computer correctly generates a random value, but when I guess it, it gets stuck in an infite loop of guess lower guess lower guess lower etc. How do I stop this? Thanks!
1 个评论
SATHISH KUMAR M
2019-10-29
编辑:SATHISH KUMAR M
2019-10-29
u can use IF loop to get ur answer......
but in here i think u have to use "BREAK" to stop infinite loop
回答(3 个)
galaxy
2019-10-29
Let 's try
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
end
5 个评论
Muhammad Waheed AZAM
2022-10-26
this code always give 82 number is correct can you help me to improve please
x=randi(100);
y=input(number);
while (1)
number='guess the number between 1 and 100=';
if (y>x)
disp('your guess is higer');
elseif (y<x)
disp('your guess is lower');
else
disp('your guess is correct');
break;
end
end
Image Analyst
2022-10-26
Try this:
trueNumber = randi(100);
userPrompt = 'Guess the number between 1 and 100 : ';
maxGuesses = 7;
numGuesses = 0;
usersGuess = input(userPrompt);
while numGuesses < maxGuesses
if (usersGuess > trueNumber)
fprintf(' Your guess of %d is too high.\n', usersGuess);
elseif (usersGuess < trueNumber)
fprintf(' Your guess of %d is too low.\n', usersGuess);
elseif usersGuess < 0
break; % Quit if they enter a negative number or try more than 6 times.
else
fprintf(' Your guess is %d is correct.\n', usersGuess);
break;
end
numGuesses = numGuesses + 1;
% Let them try again
userPrompt = sprintf('Attempt #%d. Guess the number between 1 and 100 : ', numGuesses);
usersGuess = input(userPrompt);
end
0 个评论
Bhaskar R
2019-10-29
Here you have made some mistakes
1) Gerenating vector instead of single random number
y=randi(1,100); % Which generates the 1x100 vector not a single random number
Here use single interger random value as
y = randi(100); % correct way to get a random value between 1, 100(100 is max limit value)
2) While loops
What is the need to use while loop, you can go with if else condition
If necessory, put break keyword in each while loop.
3) comparing single user input value x to y vector in while loop condition checking
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!