开发者

Why do these nested while loops not work?

I tried and tried and trie开发者_运维百科d to get this code to work and kept coming up with zilch. So I decided to try it using "for loops" instead and it worked first try. Could somebody tell me why this code is no good?

<?php
$x = $y = 10;

while ($x < 100) {
    while ($y < 100) {
        $num = $x * $y;
        $numstr = strval($num);
        if ($numstr == strrev($numstr)) {
            $pals[] = $numstr;
        }
        $y++;
    }
    $x++;   
}
?>


you should reset y=10 inside the first while.

$x = 10;

while ($x < 100) {
    $y = 10;
    while ($y < 100) {
        $num = $x * $y;
        $numstr = strval($num);
        if ($numstr == strrev($numstr)) {
            $pals[] = $numstr;
        }
        $y++;
    }
    $x++;   
}


You need to reset y before the y loop begins.

While($x < 100){
 $y=10; //... rest of code


For loops which loop over an integer that is incremented I would prefer the for-loop:

for ($x=0; $x < 100; $x++) {
  for ($y=10; $y<100; $y++) {
    $num = $x * $y;
    $numstr = strval($num);
    if ($numstr == strrev($numstr)) {
      $pals[] = $numstr;
    }
  }  
}

IMHO this is much more readable and it's shorter, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜