I have three comments:
If your intent is to generate random integers, do not use rand
. This generates floating point numbers in the range of [0,1]
and if you scaled this number so that it confirms to a minimum and maximum range, the floating point errors will prevent you from properly doing an equality comparison. Check out this canonical Stack Overflow post: Why is 24.0000 not equal to 24.0000 in MATLAB?. If you want to generate random integers, use randi
for that instead. You can actually specify the smallest and largest integer to be generated directly, which is inputted as a two-element array.
Inside the while
loop is where you should be generating the number. You only generate the number once outside of the while
loop and this will only exit if you manage to generate the desired number on the first try. This will hang indefinitely otherwise.
Make the tries
variable just a scalar. You just want to accumulate how many times it required to guess. Do the same thing for randnumber
. From what I can see in your code, you are not required to remember the history of each guess.
With the above comments, do something like this instead:
minumber = input('Please enter a minimum value: ');
maxnumber = input('Please enter a maximum value: ');
choicenumber = input('Please enter your choice in this range: ');
randnumber = randi([minumber maxnumber], 1); % Change
tries = 1; % Change
while randnumber ~= choicenumber
randnumber = randi([minumber maxnumber], 1); % Regenerate number
tries = tries + 1; % Change
end
fprintf('It took %d tries to generate your number.\n', tries); % Change
I put the above code into a test script called test_random.m
and ran it a few times. Here are some sample runs I ran with your desired inputs:
>> test_random
Please enter a minimum value: 1
Please enter a maximum value: 10
Please enter your choice in this range: 5
It took 4 tries to generate your number.
>> test_random
Please enter a minimum value: 1
Please enter a maximum value: 10
Please enter your choice in this range: 5
It took 10 tries to generate your number.
>> test_random
Please enter a minimum value: 1
Please enter a maximum value: 10
Please enter your choice in this range: 5
It took 16 tries to generate your number.