2015-10-06 152 views
-4

爲什麼這段代碼不能正常工作?while循環中的多個條件無法正常工作

我們在這裏有一個無限循環! 我想在連續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!"; 
+0

條件'(($ top <3)||(bottom <3))'總是'true',應該是'(($ top <3)&&($ bottom <3))' –

+0

寫$ bottom而不是bottom在while循環條件下 –

+0

@MahaDev我修復了它。這是一個打字錯誤。 –

回答

0

每次(不要緊,如果是以前是一個「頂」或「底」),那麼你重置另一個。這是錯誤的。您只需如果先前的翻蓋不同於當前的翻轉和翻轉的總數小於3在循環條件也是錯誤重置它,它應該是:

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

正如@Maha Dev所說的那樣,它應該是'$ bottom' –

+0

@HarshitShrivastava抱歉只修好了!謝謝! – itoctopus

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