Number counter game

那年仲夏 提交于 2020-05-09 17:25:09

问题


Im trying to make a random number counter game that uses a for loop to print out 6 random numbers 1 - 6. I want to make it so the code can say how many times the number 6 shows in the loop.

At the moment I have the code it prints out for a loop of 6 random numbers but it only counts the numbers printed out.

For example Welcome to the Dice Game! How many sixes will you roll? 4 2 4 6 4 6 You rolled 2 six(es)!

<?php

echo"<h1>Welcome to the guess game thing guess how many 6s!</h1>";
$counter = 0;

for ($i=0; $i <=6;$i++) { 
    $randomNum = rand(1,6);

    if ($randomNum <= 6) {
        echo "<br> $randomNum";
        $counter++;
    }

    else
    {
        echo"$randomNum  <br>";

    }
}

echo"<br>You rolled $counter sixes";

回答1:


Some minor changes but you were almost there. Being consistent with your line breaks and verifying you check specifically for 6

$numberToMatch = 6;
for ($i = 0; $i <= 6; $i++) { 
    $randomNum = rand(1,6);

    if ($randomNum == $numberToMatch) {
        $counter++;
    }

    echo "$randomNum <br>";
}



回答2:


You can do it like this:

$num = $_POST["num"];

for ($i=0; $i <=100;$i++) { 
    $randomNum = rand(1,10);

    if ($randomNum == $num) {
        echo $randomNum;
        break;
    }

    echo $randomNum;

}

echo"<h2> there are $i</h2>";


来源:https://stackoverflow.com/questions/61372570/number-counter-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!