drt3751 2013-07-02 12:54
浏览 62

PHP中的递归[关闭]

I have a function like this:

function test($T0){
  $T01 = $T0-$T0/2;
  $T02 = $T0+$T0/2;
  if($T01<$T0){
    test($T01);
  } else if($T02<$T0){
    test($T02);
  } else {}
  $result = array($T01,$T02);
    return $result;
  }

  $T0 = 50;
  $result = test($T0);
  echo $result[0];

Why this function is not recursion?

  • 写回答

5条回答 默认 最新

  • douhu2890 2013-07-02 12:57
    关注

    You are missing the return on your recursive calls:

    return test($T01);
    

    and

    return test($T02);
    

    In addition, you seem to have strange placement of braces on your else clause. Most likely it should be:

    else {
        $result = array($T01,$T02);
        return $result;
    }
    

    Finally, it's worth noting that this function will (theoretically) cause your code to recurse indefinitely, as you're just dividing a positive number in 2 all the time until it reaches 0. In theory this never happens. In practice, you'll recurse to some very-very small number at which the difference with 0 will be below the floating point precision. In my test this number was 4.9406564584125E-324 (i.e. about 0.0....0494 with ... being 322 zeros).

    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件