PHP因子问题

时间:2016-08-07 03:56:21

标签: php html forms function factorial

我正在尝试学习PHP并在给定用户输入时计算数字的阶乘,但我似乎很难过。我的第一个和最后一个条件结帐但是当我输入一个大于2的数字时,我的结果总是假的,这是我的代码:

<!DOCTYPE html>
<html>
  <head>
      <title>Factorial</title>
  </head>
  <body>
    <form action="" method="GET">
        Enter Number: <input type="text" name="num"><br>
        <input type="submit" name ="submit">
    </form>
    Factorial Of Your Number:
    <?php
      function factorial($n){

          if (ctype_digit($n))
          {
              if ($n <= 1)
              {
                  echo "1";
              }
              else
              {
                 echo $n * factorial($n - 1);
              }
          }
          else
          {
            echo "false";
          }
      }
      if(isset($_GET['submit']))
      {
        $s = $_GET["num"];
        factorial($s);
      }
    ?>
  </body>
</html>

我尝试编辑此行echo $ n * factorial($ n - 1)的许多变体;但都导致错误或错误,我似乎无法解决这个问题。有任何想法吗?请注意,我试图将php保留在内部正文中而不是externalphp文件。

2 个答案:

答案 0 :(得分:1)

要使递归函数正常工作,需要返回一个数字。否则,您的函数将尝试计算引发错误的$n * null

function factorial($n){
    if ($n <= 1) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}

if (isset($_GET['submit'])) {
    $n = intval($_GET["num"]);
    echo factorial($n);
}

答案 1 :(得分:-1)

你走了:

<?php
   $num = $_POST["num"];
   $factorial_value = 1;
   for ($x=$num; $x>=1; $x--)
   {
      $factorial_value = $factorial_value * $x;
   }
   echo "Factorial of $num is $factorial";
?> 

<form method="post">
    Enter a num: 
    <input type="text" name="num">
    <input type="submit" Value="CALCULATE YOUR FACTORIAL"> 
</form>
相关问题