Dice rolling & loops

조회 수: 114 (최근 30일)
Nina Helena
Nina Helena 2019년 10월 22일
댓글: Jon 2019년 10월 23일
Hi! Im currently solving a task in which i have to simulate dice rolling. I'm supposed to generate 10 random numbers (between 1 and 6 of course, that part I've managed to do using a=rand(1,10) and then multiplying with 6 and rounding them). The next part is writing a loop which I'm struggling with. If 5 or 6 is gotten 7 or more times its supposed to display 'gain is 2',if 5 or 6 is gotten 4,5 or 6 times then display gain is 1 and if its gotten 4 or less times then gain is 0. Any help or advice is appreciated

채택된 답변

James Tursa
James Tursa 2019년 10월 23일
편집: James Tursa 2019년 10월 23일
The loop could look something like this:
n = numel(a);
got5or6 = 0;
for k=1:n
if( _______ ) % you fill in the blank here
got5or6 = got5or6 + 1;
end
end
% you put code here to test got5or6 value and print appropriate message
You need to write code for the two places indicated above. For the if-test, the code would test to see if a(k) is equal to 5 or equal to 6. For the display part, you will write code to see which range the got5or6 value fits into and then print the appropriate message. Give this a try and then ask for more help if you need it.

추가 답변 (1개)

Jon
Jon 2019년 10월 22일
You can generate a vector with 10 dice rolls using
rolls = randi(6,1,10)
You can determine how many of the 10 rolls are either a 5 or 6 using
count = sum(rolls>=5)
I think with those ideas you could then setup your logic to branch and display the corresponing text.
  댓글 수: 2
Nina Helena
Nina Helena 2019년 10월 23일
First of all,thank you so much for taking the time out of your day to answer me!
Secondly, something along those lines and using if and elseif was my original idea but my professor said that i can only use for loop which,in all honesty, i'm struggling to incorporate in this task.
If you or anyone else has any ideas it'd be appreciated
Thank you
Jon
Jon 2019년 10월 23일
You could do the whole thing with no loops and no if statements with something like this:
gain = [0 0 0 1 1 1 2 2 2 2]
rolls = randi(6,1,10)
count = sum(rolls>=5)
disp(['gain is ',num2str(gain(count))])

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by