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!

回答(3 个)

galaxy
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
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
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

Bhaskar R
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by