function guess % % Play a guessing game with the user. Try to guess a number, % using a binary search to narrow down the value. % % At the end of the game, when we have finally found the number, % print a message describing how many guesses it took. % % Arguments: % none % % MWR 11/29/2011 % Greet the user fprintf(1, 'Hello! Please play a guessing game with me.\n'); % Set initial values % bottom and top of range of values we will guess bottom = 1; top = 100; fprintf(1, 'Please guess a number between %d and %d \n', bottom, top); % number of guesses it has taken so far guesses_so_far = 0; % LOOP done_yet = 0; while (done_yet == 0) % guess the middle of the current range guess = round((top + bottom)/2); fprintf(1, 'My guess is %3d.\n', guess); guesses_so_far = guesses_so_far + 1; % get feedback from user % 'y' for 'yes, that is correct' % 'h' for 'guess is too high' % 'l' for 'guess is too low' user_says = input('Type y if correct, h if too high, l if too low ', 's'); % incorporate the feedback if (user_says == 'y') % if we are correct, break out of the loop done_yet = 1; elseif (user_says == 'h') % if too high, re-set range to lower half of current top = guess; elseif (user_says == 'l') % if too low, re-set range to upper half of current bottom = guess; else % whoops! the user typed an invalid response fprintf(1, 'sorry, I did not understand that\n'); end % End of LOOP over guesses end % Victory! % print out the number of guesses it took