2015-04-01 221 views
-1

即時學習PHP,我無法獲得這段代碼的工作,我剛剛開始進入php,並不能弄清楚這一點。在線驗證器報告沒有發現問題,但它爲我設置了一個無限循環。有人能告訴我爲什麼$ eggUsage沒有從$蛋中減去。php從變量中減去一個變量以獲取值

謝謝:-)

<?php 

    $eggs = 12; 
    $eggUsage = 0; 

    while($eggs - $eggUsage > 0) { 
    $eggUsage = rand(0, 1, 2, 3, 4); 
    $eggs = $eggs - $eggUsage; 

    echo "You have {$eggs} left"; 
    } 

    if ($eggs < 4) { 
    $eggUsage = rand(0, 1, 2, 3, 4); 
    $eggs == $eggs - $eggUsage; 

    echo "You are almost out. BUY EGGS!"; 
    } 

    echo "<p>Congratulations, you are out of eggs.</p>" 
?> 
+0

'$ eggs = $ eggs - $ eggUsage;' – 2015-04-01 15:11:14

回答

0

rand()預計2個參數,你已經在你的代碼中給出4。 嘗試rand(0, 4)

此外,請不要忘記上次回顯中的;,並且在線$eggs == $eggs - $eggsUsage中應該有一個小錯誤,該錯誤應該是=

這段代碼工作完全正常對我來說:

$eggs = 12; 
    $eggUsage = 0; 

    while($eggs - $eggUsage > 0) { 
     $eggUsage = rand(0,4); 
     $eggs = $eggs - $eggUsage; 

     echo "You have {$eggs} left"; 
    } 

    if ($eggs < 4) { 
     $eggUsage = rand(0,4); 
     $eggs = $eggs - $eggUsage; 

     echo "You are almost out. BUY EGGS!"; 
    } 

    echo "<p>Congratulations, you are out of eggs.</p>" ; 
0

應該array_rand(0,1,2,3,4)從數組挑值,但作爲數組包含數字從0到4,rand(0,4)是確定的。

+0

謝謝你們,這真的很有幫助:-) – 2015-04-01 16:55:45