need help with a guessing iteration

7 views (last 30 days)
Jenn Garrison
Jenn Garrison on 22 Apr 2017
Answered: Walter Roberson on 22 Apr 2017
I need help with writing a function to make matlab guess a number I have picked. This is my problem "Make the computer guess your secret number. The computer asks for the range of the secret number[low high] , and then through a series of guesses that you reply with too high (H) or too low (L) or you're correct (C), the computer guesses your number" so far I have this but I am a little lost
number = input('low high');
number > low;
number < high;
while number > low
if a = randi(high);
disp (a);
else a ~= number

Answers (1)

Walter Roberson
Walter Roberson on 22 Apr 2017
"The computer asks for the range of the secret number[low high]"
Your line
number = input('low high');
is okay for that, other than the variable not being named well. But keep in mind that a vector of two values is going to be entered (if the person enters the values properly). Your later code treats number as if it is a scalar.
number > low;
You have not defined low . If you had defined it, then that line would compute whether number (the vector) is greater than low, which is an operation that would create a vector of logical values, 0 for each element in number that was less than or equal to low and 1 for each element in number that was greater than low . Then, having computed that logical vector, the semi-colon at the end of the line tells MATLAB to throw away the results. Nothing useful would have been accomplished. There is no good reason to have that line of your code, or the one after.
"and then through a series of guesses that you reply with too high (H) or too low (L) or you're correct (C),"
So the computer is supposed to guess a value in the range entered in response to your input('low high'), and it is supposed to display the guessed value. Then there should be an input statement that expects a string for input, something like,
outcome = input('enter C for correct, H for too high, L for too low', 's');
The computer should analyze the input character to figure out which situation it had, then use that knowledge to adjust its range of guesses.
if strcmpi(outcome, 'C')
disp('I''m just too good for you!')
break
elseif strcmpi(outcome, 'H')
...
elseif strcmpi(outcome, 'L')
...
else
disp('You tease! Enter C, H, or L next time!')
end

Tags

Community Treasure Hunt

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

Start Hunting!