[英]do-while loop only runs once
我试图使用一个类来获得一个简单的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;
在do while循环中运行,这意味着它只会运行一次。 $int
而不是$intStep
$int
是否小于零而不是$intStep
这是修复了所有这些问题的代码,它可以正常工作并返回15:
class Factorial {
public function calculate ($int) {
if (!is_int($int)) {
echo "entry is not a number";
}
$intStep = $int - 1;
do {
$int += $intStep;
$intStep--;
} while ($intStep > 0);
return $int;
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
在结果准备好之前,您不应该从函数中返回。 由于您提早返回,因此您将无法完成计算。
通常,如果您学习如何调试,您的生活将会更加轻松。 对于PHP,最简单的方法是在整个代码中echo
内容。 如果将echo $int
放入循环内,则对您来说更明显是什么问题。
尝试这个
<?php
class Factorial {
public function calculate($num){
$Factorial = 1;
$i =1;
do{
$Factorial *= $i;
$i++;
}while($i<=$num);
return $Factorial;
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
?>
阶乘? 也许下面的代码是您想要的:
不要忘记负数。
class Factorial {
public function calculate ($int) {
if (!is_int($int)) {
echo "entry is not a number";
}
if ($int == 0 || $int == 1) {
$result = 1;
} else if ($int < 0) {
$result = $this->calculate($int + 1) * $int;
} else {
$result = $this->calculate($int - 1) * $int;
}
return $result;
}
}
$factorial = new Factorial;
echo $factorial->calculate(-4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.