我得到了一個功能:
- 這應該添加到號$從X隨機數-25至25
- 如果結果高於255或低於0,則函數應該被再次調用以產生可接受的結果。PHP:簡單的數學函數返回空值,而不是整數
我得到的是:
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);
確實給我空有時?
我試圖檢查它,但我沒有找到原因:
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'
}
}
謝謝@Hauke。我不知道在再次調用函數之前需要返回。因爲'while'是更清潔的解決方案 - 我會使用它。再次感謝! – suz