do-while 循环只运行一次

do-while loop only runs once

我正在尝试使用 class 制作一个简单的 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 从您的函数中。由于你 return 早,你不会完成计算。

一般来说,如果您学会调试,您的生活会更轻松。对于 PHP,最简单的方法是在整个代码中添加 echo 内容。如果你把 echo $int 放在你的循环中,你会更清楚问题是什么。

我发现你的代码有很多问题:

  1. return $int; 在 do while 循环中是 运行,这意味着它只会 运行 一次。
  2. 你递减 $int 而不是 $intStep
  3. 您正在检查 $int 是否小于零而不是 $intStep

这是你的代码,所有这些问题都已修复,它可以工作 returns 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);

3v4l.org demo

试试这个

 <?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);