2010-06-06 128 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; 
    } 
    } 
} 

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