[英]do-while loop only runs once
I am trying to make a simple while loop using a class to get the factorial of a number. 我试图使用一个类来获得一个简单的while循环,以获取数字的阶乘。 However, for some reason, the while loop is only returning the value after it has run once. 但是,由于某种原因,while循环仅在运行一次之后才返回该值。
Here is my code: 这是我的代码:
<?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);
I see a number of problems with your code: 我发现您的代码存在许多问题:
return $int;
is run inside the do while loop, which means it'll only ever run once. 在do while循环中运行,这意味着它只会运行一次。 $int
instead of $intStep
您要递减$int
而不是$intStep
$int
is below zero instead of $intStep
您正在检查$int
是否小于零而不是$intStep
Here's your code with all of these problems fixed, it works and returns 15: 这是修复了所有这些问题的代码,它可以正常工作并返回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);
You shouldn't return from your function until your result is ready. 在结果准备好之前,您不应该从函数中返回。 Since you return early, you won't finish your calculation. 由于您提早返回,因此您将无法完成计算。
In general, your life will be easier if you learn how to debug. 通常,如果您学习如何调试,您的生活将会更加轻松。 For PHP, the easiest way would be to echo
stuff throughout your code. 对于PHP,最简单的方法是在整个代码中echo
内容。 If you put echo $int
inside of your loop it would be more obvious to you what the issue was. 如果将echo $int
放入循环内,则对您来说更明显是什么问题。
try this 尝试这个
<?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);
?>
Factorial ? 阶乘? Maybe the following code is what you want: 也许下面的代码是您想要的:
Don't forget negative Numbers. 不要忘记负数。
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.