2

我的名为 RollDice 的函数模拟了给定数量的六面骰子的滚动给定次数。该函数有两个输入参数,每个实验中将掷出的骰子数 (NumDice) 和掷骰子的总次数 (NumRolls)。该函数的输出将是一个长度为 NumRolls 的向量 SumDice,其中包含每个实验中骰子值的总和。

这是我现在的代码:我如何计算骰子的总和?谢谢!

function SumDice= RollDice(NumDice,NumRolls)

FACES= 6;               
maxOut= FACES*NumDice;         
count= zeros(1,maxOut);  


for i = 1:NumRolls

    outcome= 0;  
    for k= 1:NumDice
        outcome= outcome + ceil(ranNumDice(1)*FACES);
    end

    count(outcome)= count(outcome) + 1;
end


bar(NumDice:maxOut, count(NumDice:length(count)));
message= sprintf('% NumDice rolls of % NumDice fair dice',  NumRolls, NumDice);
title(message);
xlabel('sum of dice values');  ylabel('Count');
4

1 回答 1

4

这是一个简单而整洁的小问题(+1),我很喜欢研究它:-)

有很多地方我觉得我可以改进你的功能。与其一一浏览,我想我只是重写函数我会怎么做,我们可以从那里开始。我把它写成一个脚本,但它可以很容易地变成一个函数。最后,我还通过允许骰子有任意数量的面(6 个或其他)来概括它。所以,这里是:

%#Define the parameters
NumDice = 2;
NumFace = 6;
NumRoll = 50;

%#Generate the rolls and obtain the sum of the rolls
AllRoll = randi(NumFace, NumRoll, NumDice);
SumRoll = sum(AllRoll, 2);

%#Determine the bins for the histogram
Bins = (NumDice:NumFace * NumDice)';

%#Build the histogram
hist(SumRoll, Bins);
title(sprintf('Histogram generated from %d rolls of %d %d-sided dice', NumRoll, NumDice, NumFace));
xlabel(sprintf('Sum of %d dice', NumDice));
ylabel('Count');

我建议您仔细查看我的代码和我使用的每个函数的文档。将来在解决 Matlab 中的其他问题时,该练习可能对您有用。完成后,如果您有任何不明白的地方,请在评论中告诉我,我会尽力提供帮助。干杯!

ps,如果您不再需要参考单个卷,您当然可以将AllRollandSumRoll行转换为单行,即:SumRoll = sum(randi(NumFace, NumRoll, NumDice), 2);. 我个人认为两行更易读,我怀疑它会对代码的效率产生很大影响。

于 2012-11-21T04:19:30.097 回答