如何编写代码来掷出一个六面骰子,并将显示的两个数字相加以产生 2 到 12 之间的和?然后绘制它
此代码适用于 10 次观察。您可以根据您的标准进行更改。
for i =1:1:10
first_no = randi([1 6],1);
second_no = randi([1 6],1);
if second_no == first_no
second_no = randi([1 6],1);
end
sum(i) = first_no + second_no
no(i) = 1
end
figure;
plot(no, sum)
您只需要定义两个变量,它们取 1-6 之间的随机值。一开始,您可以选择观察次数。请参阅下面的代码:
no_obs = 5;
for i=1:no_obs
num1 = randi([1 6],1);
num2 = randi([1 6],1);
sum(i) = num1 + num2;
end
display(sum);
figure;
plot(sum)
randi()
即可立即卷一卷。
% Assumes identical dice
Num_sides = 6;
Num_dice = 2;
% One Roll of Two Dice
Roll = randi([1 Num_sides],Num_dice,1);
Total_Pips = sum(Roll);
这使得可以在一行中写入:
sum(randi([1 Num_sides],Num_dice,Num_rolls));
% Many Rolls of Two Dice
Num_rolls = 1000;
Total_Pips = sum(randi([1 Num_sides],Num_dice,Num_rolls));
histogram(Total_Pips)
ax = gca;
ax.XTick = [2:12];
xlabel('Total Pips')
ylabel('Number of Rolls')
title([num2str(Num_rolls) ' rolls of ' num2str(Num_dice) 'x ' num2str(Num_sides) '-sided dice'])