フィルターのクリア

Using for loop to match generated random numbers to an input value

7 ビュー (過去 30 日間)
Mark Coughlin
Mark Coughlin 2020 年 4 月 28 日
編集済み: James Tursa 2020 年 4 月 28 日
Hi, I want to write a script which will prompt the user for minimum and maximum integers, and then another integer which is the user’s choice in the range from the minimum to the maximum. I then want the srcipt to generate random integers in the range from the minimum to the maximum until a match for the user’s choice is generated and print how many random integers had to be generated until a match for the user’s choice was found.
I am confused as to how to identify n, which is the number of iterations. Any suggestions would be greatly appreciated! This is my script so far:
function findmine
imin=input('Please enter your minimum value: ');
imax=input('Please enter your maximum value: ');
choice=input('Now enter your choice in this range: ');
% n=number of attempts
for i=1:n
x(i)=randi([imin imax]);
if x(i)==choice
formatSpec='It took %d tries to get your number\n';
fprintf(formatSpec,n);
else
end
end
end

採用された回答

James Tursa
James Tursa 2020 年 4 月 28 日
編集済み: James Tursa 2020 年 4 月 28 日
Since you don't know ahead of time how many tries it will take, this is best done with a while loop instead of a for loop. E.g.,
n = 0;
while( true )
x=randi([imin imax]);
n = n + 1;
And when you get a match, use a break statement to get out of the while loop.

その他の回答 (1 件)

Steven Lord
Steven Lord 2020 年 4 月 28 日
You have no control over how many iterations it will take to match the number the user chose, so a for loop (which has an upper bound that is set when you enter the loop on how many iterations it can run) is not the best choice of a control structure in this case.
A while loop doesn't have such an inherent upper bound, so I'd use that instead.
You probably also want to validate the user's inputs. randi can only generate integer values, so what if the user chose to enter 1.5 as their choice? What if they chose 42 as their number "in the range" 1 to 10?

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by