生成1-100之间的随机数,当它达到99时停止并计算它所花费的数量

时间:2018-02-10 17:06:04

标签: php loops

我目前正致力于一些我真正需要帮助的事情。我会做一段时间或做while循环,使用rand功能生成1到100之间的随机数。当随机数达到99时,循环应该停止并显示尝试达到数字99所需的尝试次数,如下所示: / p>

“尝试击中99号”需要53次尝试

如果有人可以帮我解决一个简单的解决方案,我将非常感激!

3 个答案:

答案 0 :(得分:1)

像这样的简单循环应该是你所追求的

$count=0;
$i=0;
$target=99;

while( $i!=$target ){
    $i=rand(1,100);
    $count++;
}
printf('it took %u attempts to reach %u',$count,$target);

答案 1 :(得分:1)

for循环适用于此;

for ($count = 1; rand(1, 100) != 99; $count++);
echo "It took {$count} attempts to hit the number 99";

示例输出;

It took 47 attempts to hit the number 99

答案 2 :(得分:0)

在我的代码中,我声明flag变量的值为true。 while循环将继续并在$ arrRandNum中添加推送值,直到随机值为99.

99生成后,将标志值设置为false,循环将终止。

<?php
    $flag = true;
    $randNum;
    $arrRandNum = array();
    while($flag){

        $randNum = rand(1,100);
        if(99 !== $randNum){
            array_push($arrRandNum,$randNum);
        }else{
            $flag = false;
        }
    }
    print_r("total attempts: ".count($arrRandNum)."<br/>");
    print_r($arrRandNum);
?>