模拟滚动模具1000次的程序,告诉您每个数字滚动的次数

时间:2017-09-21 22:42:16

标签: php html

    <body>
<?php


$face1 = "1";
$face2 = "2";
$face3 = "3";
$face4 = "4";
$face5 = "5";
$face6 = "6";

$frequency1 = 0;
$frequency2 = 0;
$frequency3 = 0;
$frequency4 = 0;
$frequency5 = 0;
$frequency6 = 0;
$result = rand(1, 6);

if ($result = 1)
    $frequency1+=1;
if ($result = 2)
    $frequency2+=1;
if ($result = 3)
    $frequency3+=1;
if ($result = 4)
    $frequency4+=1;
if ($result = 5)
    $frequency5+=1;
if ($result = 6)
    $frequency6+=1;
?>


        <h2>Statistical analysis of results from rolling a
six‐sided die</h2>

        <table width='600' border='1' cellspacing='0' cellpadding='0' align='center'>
            <tr>
                <th>Face</th>
                <th>Frequency</th>
            </tr>
            <?php
            define("FACE_NUM", 6);
            $face_count=1; 
            while ($face_count<=FACE_NUM) {
                $number = ${'face' . $face_count};
                $frequency = ${'frequency' . $face_count};

                echo "<tr>
                        <td> $number </td>
                        <td> $frequency </td>
                     </tr>";

                $face_count++;
                }
            ?>
        </table>
        <input type="submit" value="Refresh" onclick="window.location.reload()" />  

    </body>
</html>

当我在浏览器中测试它时,它只显示列中显示频率的数字1。如何使其滚动1,000次然后显示频率?我错过了什么?

我们应该使用至少一个循环,因此答案中需要这样做。模具上每个数字的频率需要显示在表格中。

2 个答案:

答案 0 :(得分:3)

我想从头开始解决你的问题。

$freqs = [0,0,0,0,0,0]; // array in which you save the frequency of each face

for ($i = 0; $i < 1000; ++$i) {
    ++$freqs[rand(0,5)];
}

// then just print the array freqs (by dividing the values with 1000 if needed

答案 1 :(得分:1)

实际错误:

此行中的一个即时错误(以及所有类似的行):

if ($result = 4)

=运算符是分配,因此您不会检查$ result是否等于4,但是您将$ 4分配给$ result。该赋值的结果也是4,其值为true,因此无论$ result的初始值如何,总是会增加$ 4频率。

缺少的循环

要执行1000次抛出,您应该拥有1000份代码,但只需要一个循环。您甚至可以引入更多循环,因为每个面也有相同的代码,并且使用循环您不需要复制该代码6次。如果你要改变20面骰子的程序怎么办?它会变得巨大!而是使用循环和数组。

附加的优势是您的程序更灵活。您只需要更改一个数字,使其适用于具有更多面部的奇数骰子。您甚至可以询问用户他的骰子有多少面孔,并将该数字放在$ faces变量中。

这里有一些示例代码。它可能更短,因为您可以使用一些PHP魔法初始化结果数组,但是完整地写出它仍然非常紧凑,并且希望更清楚发生了什么。

// Config. Hard coded numbers now, next step is to read them from $_GET.
$faces = 6;
$throws = 1000;

// Initialize results. It's an array where the face number is the index.
for($f = 1; $f <= $faces; $f++) {
  $results[$f] = 0;
}

// Do a lot of throws
for ($t = 0; $t < $throws; $t++) {
  // The actual throw.
  $face = rand(1, 6);
  // Incrementing the counter for that face.
  $results[$face]++;
}

// Print the results
echo "Result of throwing a $faces faced dice $throws times:";
print_r($result);