其他循环带有意外输出

时间:2015-12-01 15:17:51

标签: php algorithm recursion factorial

我已经使用了此代码,但我并不了解输出。我期待输出121。 我希望了解这个特定的功能而不是因子功能。

代码:

(int)scrollView.contentOffset.x % 1024;

输出:

function a($num) {
    static $totFac = 1;

    if($num > 0){
        $totFac = $totFac * $num;
        a($num - 1);
    }

    $totFac++;
    return $totFac;
}

$result = a(5);
echo 'result: '.$result;

2 个答案:

答案 0 :(得分:3)

  • 首先,5的阶乘被解释为:

    5! = 5 x 4 x 3 x 2 x 1 = 120
    
  • 其次,这是使用递归调用时的阶乘:

    function factorial($number) {
        if ($number < 2) { 
            return 1; 
        } else { 
            return ($number * factorial($number-1)); 
        } 
    }
    
  • 如果你不是指阶乘,那么如果我改变你的功能就会发生这种情况

    function a($num) {
        static $totFac = 1;
    
        if($num > 0){
            $totFac = $totFac * $num;
            echo "calc totFac: " . $totFac . "\n";
            a($num - 1);
        }
    
        $totFac++;
        echo "increment totFac: " . $totFac . "\n";
       return $totFac;
    }
    
    $result = a(5);
    echo 'result: '.$result;
    

这是echo

的输出
calc totFac: 5
calc totFac: 20
calc totFac: 60
calc totFac: 120
calc totFac: 120
increment totFac: 120
increment totFac: 121
increment totFac: 122
increment totFac: 123
increment totFac: 124
increment totFac: 125
result: 126

答案 1 :(得分:0)

<?php
function a($num) {
    static $totFac = 1;
    if($num > 0){
        $totFac = $totFac * $num;
        echo 'totfac: '.$totFac . "<br>";
        return a($num - 1); //you have to return here to stop execution
    } else {
        $totFac++;
        return $totFac;
    }
}
$result = a(5);
echo 'result: '.$result;
?>

查看解释说明