简体   繁体   English

我怎样才能把它写成一个 while 循环? PHP

[英]How can i write this as a while loop? PHP

<?php
for ($i=0; $i<10; $i++) {
    $number = mt_rand(1, 100);
    if ($number %2== 0) {
        $result = 'even';
    } else {
        $result = 'odd';
    }
    echo $number.' '.'('.$result.')'.'<br>';
}?>

I want to write it in a while loop form this is as far as i have gotten.我想以 while 循环形式编写它,这是我所得到的。 It just prints one random number and nothing else.它只打印一个随机数,仅此而已。 I am using phpStorm and edge browser on PHP8.1.我在 PHP8.1 上使用 phpStorm 和边缘浏览器。

<?php

$i=0;
while ($i<10) {
  if ($number=mt_rand(1,100)) {
    $result = 'even';
  } else {
    $result = 'odd';
  }
  $i++;
  echo $number.' '.'('.$result.')'.'<br>';
}
    
?>

The main reason that the code is not working is that you are assigning the $number = mt_rand(1,100) inside the if() condition.代码不起作用的主要原因是您在if()条件内分配了$number = mt_rand(1,100)

So everytime you execute if then it will not compare but it'll keep assigning the $number variable.所以每次你执行 if then 它都不会比较,但它会继续分配$number变量。 I have separated the assignment and comparison logic.我已经分离了分配和比较逻辑。

Try This:尝试这个:

<?php

    $i=0;
    while ($i<10) {
        $number = mt_rand(1,100);
        if ($number % 2 == 0) {
            $result = 'even';
        } else {
            $result = 'odd';
        }
        $i++;
        echo $number.' '.'('.$result.')'.'<br>';
    }

i changed to 10 to make case: the script you use can generate numbers can repeat;我改为 10 以说明情况:您使用的脚本可以生成数字可以重复; the second script i put generates unique random numbers(in case you need);我放的第二个脚本会生成唯一的随机数(如果需要); by uncomment //$max=100;通过取消注释//$max=100; and commenting $max=10;并评论$max=10; the second script will generate UNIQUE NUMBERS in range 1..100第二个脚本将在 1..100 范围内生成 UNIQUE NUMBERS

  <?php


/*the first script*/    
    $max=100;
    //$max=10;
    
    
    $i=0;
    while ($i<10) {
      if (($number=mt_rand(1,$max))and(($number % 2) ==0)) {
        $result = 'even';
      } else {
        $result = 'odd';
      }
      $i++;
      echo $number.' '.'('.$result.')'.'<br>';
    }
      
    echo '<hr>';
        
    /*the second script : unique numbers*/
    $nrs=range(1,$max);
    $i=-1;while($i++<9){
        $pos=mt_rand(0,count($nrs)-1);
        $nr=$nrs[$pos];
        unset($nrs[$pos]);
        rsort($nrs);
        echo $nr.'-'.(($nr%2)==0?'even':'odd').'<br>';
    }
    
    ?>

i did this:我这样做了: 解决方案同时扣

Please, check me if my answer help you.请检查我的答案是否对您有帮助。 Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM