迭代在我想要它之前打破

时间:2012-01-26 05:35:19

标签: php html iteration

我试图让程序重复,直到$ he​​ads变量和$ tails变量都大于0.我无法弄清楚我做错了什么。只需一次迭代,while循环就会被破坏。

<?php
echo "<table border=\"1\">";
echo "<tr><td>Person</td><td>Heads</td><td>Tails</td><td>Total</td></tr>";



for ($person=1; $person < 11; $person++){
echo "<tr><td>Person $person </td>";
$both = 0;
$heads = 0;
$tails = 0;
$total = 0;
while ($both < 1){
    do {
        $total++;
        $random = rand(1,2);
        if ($random == 1){
            $heads++;
        } else{
            $tails++;
        }  
    } while (($tails < 0)  && ($heads < 0));
    $both = 1;

}
echo "<td>$heads</td><td>$tails</td><td>$total</td>";
echo "</tr>";

}

echo "</table>";

?>

2 个答案:

答案 0 :(得分:2)

在这一行

} while (($tails < 0)  && ($heads < 0));

似乎$tails$heads都不会严格低于0,因此始终为假。请尝试<= 0

另外,从逻辑上讲,如果这些条件的 为真,你想再次循环,对吧?因此,请使用||代替&&

结果:

} while (($tails <= 0) || ($heads <= 0));

另外,我对while ($both < 1)循环有点好奇。您似乎在循环之前分配$both = 0,并在迭代结束时分配$both = 1。这样可以保证循环只执行一次,在这种情况下 - 循环的重点是什么?也许这就是目前尚未完成的代码?

答案 1 :(得分:0)

所以你想继续翻转硬币,直到你得到至少一个头至少一个尾部结果?同时跟踪你翻转的次数?

我会像这样编码:

$heads = 0;
$tails = 0;
$total = 0;

while( true ) {
    $total ++;
    $random = rand( 0, 1 ); // 0 for tail, 1 for head
    if( $random ) $heads ++;
    else          $tails ++;

    if( $heads >= 1 && $tails >= 1 ) break;
}

while循环将继续无限运行,直到$ he​​ads和$ tails变为一个或更多。