下面的函数返回INF
作为结果。我猜这是因为数字太大了,但我该怎么解决呢?
class Factoriel {
public function calculate() {
if(func_num_args() != 1)
throw new Exception ("Invalid arguments count for method calculate!");
if(($n = (int)func_get_arg(0)) <= 0)
throw new Exception ("Invalid argument supplied for method calculate!");
$result = 1;
foreach(range(1, $n) as $current)
$result = $this->multiply ($result, $current);
return $result;
}
private function multiply($left, $right) {
return $left * $right;
}
}
$factoriel = new Factoriel();
echo $factoriel->calculate(1500);
您可以使用bcmul函数进行乘法运算,如
return bcmul("$left","$right");
代替
return $left * $right;
参见DEMO of fact(500);
1500的阶乘对于PHP来说太大了,这就是为什么你得到INF,意思是一个无限的数字。浏览http://php.net/manual/en/function.is-infinite.php