Number guessing function using while and if else functions

while x>a || x<a
%This classifies the user's input if the guess is above or below the program will tell the user their guess is incorrect
if x>a || x<a
%This classifies the user's input if the guess is above or below the program will tell the user their guess is incorrect
disp('You are to high/low please guess again \n')
else x=a
disp('You''ve got it!')
end
I'm wanting to run a program that uses a random number and outputs if the user defined input is a correct guess or else the program prompts the user to keep inputting guesses until they are correct.

댓글 수: 5

while x>a || x<a
is the same as
while ~isnan(x) && x ~= a
Anyhow, you did not ask us a question.
Our question would probably be "Where are you accepting input from the user?"
I'm sorry this is the full code I have for the problem. Right now it asks the user once and then you can't keep inputting until you're right. How do I make it so the user has to still input an answer until they match the correct random variable?
function guessing
a=randi(20); %Output one random number.
disp('I am thinking of a number between 1 and 20 \n') %Displays text
x=input('Input your guess \n');% Asks user to input a number
if x>a
%This classifies the user's input if the guess is above or below the program will tell the user their guess is incorrect
disp('You are to high guess again \n')
elseif x>a
disp('You''re too high, guess again')
elseif x == a
disp('You''ve got it!')
else x=input('Input your guess \n');
end
if x<a
disp('You are too low guess again \n');
elseif x>a
disp('You''re too high, guess again')
elseif x == a
disp('You''ve got it!')
else x=input('Input your guess \n');
end
end
while x ~= a
if x > a
too high
else
too low
end
input a new guess
end
just right
The code doesn't seem to be working.
function guessing
a=randi(20); %Output one random number.
disp('I am thinking of a number between 1 and 20 \n') %Displays text
x=input('Input your guess \n');% Asks user to input a number
while x ~= a
if x > a
%This classifies the user's input if the guess is above or below the program will tell the user their guess is incorrect
disp('You are to high guess again \n')
else x > a
disp('You''re too high, guess again')
end
x=input('Enter a new guess \n')
end
disp('Are you a jedi? You guessed right!')
The function does not settle on a number
else x > a
means the same thing as
else
disp(x > a)
Both branches of your code talk about the person being too high, with no branch saying they are too low.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

질문:

2019년 3월 22일

댓글:

2019년 3월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by