PHP:简单的数学函数返回null而不是整数

时间:2014-07-20 18:07:01

标签: php function

我有一个功能:
- 应该从-25到25添加数字$ x随机数
- 如果结果高于255或低于0,则应再次调用该函数以产生可接受的结果。

我得到的是:

function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0) 
    {
        changeParam($base_val); //is it correct?
    } 
    else 
    {   
        $new_val = $base_val + $plus;
        return $new_val;        
    }   

}

为什么:

$x = changeParam(255);
var_dump($x);

有时会给我 null 吗?

我试过检查一下,但我找不到原因:

function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0) 
    {
        changeParam($base_val);
    } 
    else 
    {   
        $new_val = $base_val + $plus;
        echo 'Is there a problem? ' . $new_val;   // this line shows correct new_val
        var_dump($new_val);                       // correct, for instance: 'int 250'
        return $new_val;                           // but in the same time, the result = 'null'
    }   

}

2 个答案:

答案 0 :(得分:3)

如果您真的想要使用递归,则必须在调用return之前添加changeParam($base_val);。所以它看起来像这样:

function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0) 
    {
        return changeParam($base_val); // CHANGED HERE
    } 
    else 
    {   
        $new_val = $base_val + $plus;
        return $new_val;        
    }   

}

但是,在这种情况下递归可能会很糟糕。 (如果搜索随机变量恰好返回&#34;错误&#34;值太多次,则可能会遇到堆栈溢出异常。在这种特定情况下发生这种情况的可能性非常低 - 但是你应该总是考虑这种情况。)

相反,你应该采用迭代方法,例如:

function changeParam($base_val)
{
    $plus = mt_rand(-25, 25);

    while (($base_val + $plus) > 255 || ($base_val + $plus) < 0) 
    {
        $plus = mt_rand(-25, 25);
    } 

    $new_val = $base_val + $plus;
    return $new_val;        
}

答案 1 :(得分:1)

function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0) 
    {
        $new_val = changeParam($base_val);
    } 
    else 
    {   
        $new_val = $base_val + $plus;   
    }   

    // return here
    return $new_val;     

}