【问题标题】:php subtracting a variable from a variable to get the valuephp从变量中减去变量以获取值
【发布时间】:2015-04-01 15:10:47
【问题描述】:

我正在学习 PHP,但我无法让这段代码工作,我刚刚开始接触 php,无法弄清楚这一点。在线验证器报告未发现任何问题,但它为我设置了无限循环。有人能告诉我为什么没有从 $eggs 中减去 $eggUsage。

谢谢你:-)

<?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>"  
?>

【问题讨论】:

  • $eggs = $eggs - $eggUsage;

标签: php variables random infinite-loop


【解决方案1】:

rand() 需要 2 个参数,您在代码中给出了 4 个。 试试rand( 0, 4 )

另外,不要忘记你上次回显中的;,你在$eggs == $eggs - $eggsUsage这行有一个小错误,应该是=

这段代码 sn-p 对我来说非常好用:

    $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>" ;

【讨论】:

    【解决方案2】:

    应该是array_rand(0,1,2,3,4)从数组中取值,但是由于数组包含从0到4的数字,rand(0,4)是可以的。

    【讨论】:

    • 谢谢你们,这真的很有帮助:-)
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多