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 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类