2010-06-06 101 views
2

我试过并尝试过,并试图让这个代码工作,并不断提出zilch。所以我决定尝试使用“for循环”代替,并且它首先尝试。有人能告诉我为什么这个代码不好吗?为什么这些嵌套的while循环不起作用?

<?php 
$x = $y = 10; 

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

回答

10

您应该在第一次重置y = 10时。

$x = 10; 

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

就这么简单?我把y变量放在错误的地方? – aliov 2010-06-06 00:46:37

+1

好吧,你只设置一次..无论如何,如果你正在寻找x * y的回文,你可能想避免检查_both_ x * y和y * x,所以我会设置$ y = $ x而不是$ Y = 10。 – 2010-06-06 00:53:14

2

您需要在y循环开始之前重置y。

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

For循环,其循环遍历被递增我宁愿for循环的整数

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

恕我直言,这是更具可读性和它的短,太多。

相关问题