【发布时间】:2018-12-13 14:45:37
【问题描述】:
我正在尝试使用一个类来制作一个简单的 while 循环来获取数字的阶乘。但是,由于某种原因,while 循环仅在运行一次后才返回值。
这是我的代码:
<?php
class Factorial {
public function calculate($int){
$intStep = $int-1;
do {
$int*=$intStep;
$int--;
return $int;
} while($int>0);
if (!is_int($int)){
echo "entry is not a number";
}
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
【问题讨论】:
-
return $int;行导致函数返回该值。当您从它返回时,该函数不会继续执行。 -
return表示退出函数。这就是为什么你的循环只运行一次,因为你正在退出循环中的函数。
标签: php class while-loop do-while factorial