使用PHP do/while语句


Using PHP do/while statement

我试图写一个简单的do/while语句,它创建一个随机数,然后检查该数字是否低于一定的阈值,如果它是while循环应该停止。然而,它似乎不适合我,我不知道为什么。

我猜它会是一些非常简单的东西,但我现在没有线索。

这是我的代码,帮助将非常感激!

<!DOCTYPE html>
<html>
    <head>
        <title>Your own do-while</title>
        <link type='text/css' rel='stylesheet' href='style.css'/>
    </head>
    <body>
    <?php
    $rayBans = rand(0,70);
    $correctPrice = false;
    do {
        echo "<p> Lets hope I can get ray bans for under £30! </p>";
    }
    while ($correctPrice == false);
        if ($rayBans > 30) {
        echo "<p> raybans at $rayBans are too expensive </p>";
        $correctPrice == false;
    }
    else if ($rayBans < 30){
        echo "<p> Finaly got my rayBans for $rayBans </p>";
        $correctPrice == true;
    }

    ?>
    </body>
</html>

在比较时,我们应该使用==在赋值给变量时我们需要=所以在你的例子中

do 
{
//You should write something so that $correctPrice becomes true
//as of now it seems to be a infinite loop
echo "<p> Lets hope I can get ray bans for under £30! </p>";
}while ($correctPrice == false);

我相信你需要这样做

<?php
    $correctPrice = false;
    do 
    {
        $rayBans = rand(0,70);
        echo "<p> Lets hope I can get ray bans for under £30! </p>";
        if ($rayBans > 30) 
        {
            echo "<p> raybans at $rayBans are too expensive </p>";
            $correctPrice = false;
        }
        else if ($rayBans < 30)
        {
            echo "<p> Finaly got my rayBans for $rayBans </p>";
            $correctPrice = true;
        }       
    }while ($correctPrice == false);
?>

纠正你的代码在do-while循环中添加条件

    echo "<p> Lets hope I can get ray bans for under £30! </p>";
    $correctPrice = false;
    do {
        $rayBans = rand(0,70);
        if ($rayBans > 30) {
            echo "<p> raybans at $rayBans are too expensive </p>";
            $correctPrice = false;
        }
        else if ($rayBans < 30){
            echo "<p> Finaly got my rayBans for $rayBans </p>";
            $correctPrice = true;
        }

    }
    while ($correctPrice == false);