2014-12-06 51 views
0

在遞歸函數中返回值時出現問題。但我可以迴應它。 這有什麼不對?在遞歸函數中返回值的問題PHP

function calculate($i,$count=1) 
{ 
    $str_i = (string)$i; 
    $rslt = 1; 

    for ($k=0; $k<strlen($str_i); $k++) { 
     $rslt = $str_i[$k]*$rslt; 
    } 

    if (strlen((string)$rslt) > 1) { 
     $this->calculate($rslt,++$count); 
    } elseif (strlen((string)$rslt) == 1) { 
     return $count; 
    } 
} 
+0

這個功能的目標是什麼?你能提供一個測試輸入嗎?如果'strlen((string)$ rslt)== 0',則永遠不會返回。 – 2014-12-06 01:24:51

+0

感謝您的回覆!這個函數計算加德納的數字! – Alliswell 2014-12-06 10:06:44

回答

1

在你if代碼不使用遞歸調用的返回值。您不要將其設置爲值或return它。因此除基本情況外的每個調用都不返回值。

試試這個:

function calculate($i,$count=1) 
{ 
    $str_i = (string)$i; 
    $rslt = 1; 

    for ($k=0; $k<strlen($str_i); $k++) { 
     $rslt = $str_i[$k]*$rslt; 
    } 

    if (strlen((string)$rslt) > 1) { 
     return $this->calculate($rslt,$count+1); // I changed this line 
    } elseif (strlen((string)$rslt) == 1) { 
     return $count; 
    } 
} 

現在我們回到由遞歸調用的返回值。注意我將++$count更改爲$count+1,因爲在使用遞歸時它是不好的樣式。

+0

是的,它的工作原理!謝謝你,你搖滾!抱歉,由於我的評分較低,無法投票答覆(再次謝謝!) – Alliswell 2014-12-06 09:04:19

+0

@Alliswell不客氣,如果您發現答案有用,請考慮[接受答案](http://meta.stackexchange的.com /一個/232765分之5235) – Sylwester 2014-12-06 12:38:20