while循环中的多个条件无法正常工作

时间:2015-10-06 11:41:20

标签: php while-loop

为什么这段代码不能正常工作?!

我们这里有一个无限循环! 我想在连续3个顶部或3个底部(实际上是硬币的顶部和底部)时完成循环。

<?php
$top = 0;
$bottom = 0;
$flipCount = 0;
while (($top < 3) || ($bottom < 3)) {
    $flip = rand(0,1);
    $flipCount ++;
    if ($flip){
        $top++;
        $bottom = 0;
        echo "<div>top</div>";
    }
    else {
        $bottom++;
        $top = 0;
        echo "<div>bottom</div>";
    }
}
echo "$flipCount flips!";

2 个答案:

答案 0 :(得分:1)

<?php
$top = 0;
$bottom = 0;
$flipCount = 0;
while (($top < 3) || ($bottom < 3)) {
    $flip = rand(0,1);
    $flipCount++;
    if ($flip){
        $top++;
        $bottom = 0;
        echo "<div>top</div>";
    }
    else {
        ++$bottom;
        $top = 0;
        echo "<div>bottom</div>";
    }

    if($top > 2 || $bottom > 2){
        break;
    }
}
echo "$flipCount flips!";

> Blockquote

答案 1 :(得分:0)

每当你有翻转时(无论以前是&#34;顶部&#34;或&#34;底部&#34;),那么你正在重置另一个。这是错的。如果前一个翻转不同于当前翻转并且翻转总数小于3,则只需要重置它。循环中的条件也是错误的,它应该是:

while (($top != 3) && ($bottom != 3))