Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to generate a number between 1 and 100, but I want it to keep regenerating that number until it equals 50, once it equals 50, then echo it out. How would I do this?

My Function:

function create() {
    $production_line = mt_rand(0, 3);
    $random1 = mt_rand(0, 9);
    $random2 = mt_rand(0, 9);
    $random3 = mt_rand(0, 9);
    $random4 = mt_rand(0, 9);
    $random5 = mt_rand(0, 9);
    $random6 = mt_rand(0, 9);
    $production_year = mt_rand(3, 4);
    $week1 = 4;
    $week2 = 8;
    $factory1 = 4;
    $factory2 = 8;

    if ($production_line + $random1 + $random2 + $random3 + $random4 + $random5 + $random6 + $production_year + $week1 + $week2 + $factory1 + $factory2 == 55) {
        return $production_line.$random1.$random2.$random3.$random4.$random5.$random6.$production_year.$week1.$week2.$factory1.$factory2;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
311 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use a simple loop:

$i = 0;
while ($rand = mt_rand(0,100)) {
    $i++;
    if ($rand == 50) {
        // found 50, so break out of the loop
        break;
    }
}

echo "It took $i iterations to find 50";

But that's a bit pointless, right? If you're just going to output 50 all the time, then why do you need to generate a random number? Just echo 50 instead. Also note that this could be a slow operation if the larger limit is a bigger number.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...