September 2010
M T W T F S S
« Dec    
 12345
6789101112
13141516171819
20212223242526
27282930  

Categories

Guessing Game in MATLAB

This algorithm creates a guessing program in MATLAB. First, it randomly picks an integer in range 1 to 10. Then, the user should guess the number as soon as possible. A counter keeps track of number of guesses made.

?View Code MATLAB
% This is a guessing game
counter=0;
real_number=rand(1);
real_number=10*real_number;
number=ceil(real_number);
 
fprintf('I am thinking a number between 1 and 10.\n');
guess=input('Guess a number: ');
 
while guess~= number
     counter = counter + 1;
     if guess>number
          fprintf('Your guess is too high!\n');
          guess=input('Guess another number: ');
     else
          fprintf('Your guess is too low!\n');
          guess=input('Guess another number: ');
     end
end
 
counter= counter + 1;
fprintf('Congratulations! You guessed the correct number in %g shots. \n', counter);

1 comment to Guessing Game in MATLAB

  • I know this post is old, but I randomly stumbled upon it while googling some Matlab stuff (I just started learning it). Here’s a quick rewrite of your guessing game to make it more concise:

    counter = 0;
    number = ceil(10*rand(1));

    fprintf(‘I am thinking a number between 1 and 10.\n’);
    while (guess = input(‘Guess a number: ‘)) ~= number
    counter += 1;
    if guess > number
    fprintf(‘Your guess is too high!\n’);
    else
    fprintf(‘Your guess is too low!\n’);
    end
    end

    fprintf(‘Congratulations! You guessed the correct number in %g shots. \n’, counter+1);

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>