php for循环随机数生成器问题

时间:2017-11-21 01:14:09

标签: php for-loop random

任务:

  1. 使用for循环构建一个数组(randArray []),其中包含50个随机整数,范围为0 - 100.
  2. 使用while循环在randArray []
  3. 中构建一个包含所有奇数的新数组(oddArray [])
  4. 使用foreach循环打印oddArray []中的所有奇数。
  5. 我无法理解为什么循环的第一步不起作用

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test1-1</title>
    </head>
    <body>
        <?php
            $randArray= [];
            $value = [];
            for ($randArray= 0; $randArray<= 50; $randArray++) {
                    $value = rand(0, 100)
                    $randArray[] = $value
                }
            endfor;
            echo ($randArray);
        ?>
    </body>
    </html>
    

2 个答案:

答案 0 :(得分:0)

你可以跳过其中的一些要求,只处理奇数,rand也不是随机的。

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test1-1</title>
</head>
<body>
    <?php
    for ($i= 0; $i<= 50; $i++) {
        $value = mt_rand(0, 100);

        // odd number
        if ($value % 2 != 0) {
           echo $value.'<br>';
        } 
    }
    ?>
</body>
</html>

编辑(有关原始代码的语法问题的一些评论)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test1-1</title>
</head>
<body>
    <?php
    // $randArray set as array, but used as int
    $randArray= [];
    // $value set as array, but used as int
    $value = [];

    // $randArray is now set as an int
    for ($randArray= 0; $randArray<= 50; $randArray++) {
            $value = rand(0, 100) // <-- missing semi-colon + rand not that random, mersenne twister is better
            $randArray[] = $value // <-- missing semi-colon + treating $randArray as an array when its now an int, scala value
        }
    endfor; // whats this?

    // $randArray would be an array so you cant just echo it
    echo ($randArray);

    ?>
</body>

答案 1 :(得分:0)

遵守说明,您可以这样做

// random and odd arrays
$randArray = [];
$oddArray = [];

// For loop to get 50 random integers and push to randArray
for ($i = 0; $i <= 50; $i++) {
    $value = rand(0, 100);
    $randArray[] = $value;
}

// While loop to get odd numbers from randArray and push to oddArray
$x = 0;
while ($x <= 50) {
    if ($randArray[$x] % 2 == 1) {
        $oddArray[] = $randArray[$x];
    }
    $x++;
}

// Foreach loop to print all odd numbers
foreach($oddArray as $odds) {
    echo $odds . '<br>';
}

附注:对循环参数使用不同的变量。这非常会导致您的错误。您再次使用randArray执行循环