【问题标题】:Issue with returning value in recursive function PHP递归函数PHP中的返回值问题
【发布时间】:2015-02-04 06:48:56
【问题描述】:

在递归函数中返回值有一些问题。但我可以附和它。 这有什么问题?

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;  
    }
}

【问题讨论】:

  • 这个函数的目标是什么?你能提供一个测试输入吗?如果strlen((string)$rslt) == 0 永远不会返回。
  • 感谢您的回复!这个函数计算加德纳数!

标签: php recursion return


【解决方案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,因为在使用递归时进行变异是不好的风格。

【讨论】:

  • 是的,它有效!谢谢人,你摇滚!!抱歉,由于我的评分低,无法投票给您的答案(再次感谢您!
  • @Alliswell 不客气。如果您觉得答案有用,请考虑accepting the answer
猜你喜欢
  • 2012-03-11
  • 2020-09-09
  • 2021-03-02
  • 2011-04-20
  • 1970-01-01
  • 2011-05-23
  • 2013-09-21
  • 2010-12-08
  • 2022-11-05
相关资源
最近更新 更多