一个数的阶乘

Mih*_*hir 10 javascript

我有以下代码,但它没有给因子的完美结果你可以找到它plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 24

你必须要return有价值.干得好:

function fact(x) {
   if(x==0) {
      return 1;
   }
   return x * fact(x-1);
}

function run(number) {
    alert(fact(parseInt(number, 10)));
}
Run Code Online (Sandbox Code Playgroud)

<input type="button" value="Find factiorial" onclick="run(txt1.value)">
Run Code Online (Sandbox Code Playgroud)

(如何使它适用于我留给你的负数;)(但我总是在这篇文章中展示))

只是为了好玩,一个更正确,非递归的算法:

function fact(x) {
       if(x == 0) {
           return 1;
       }
       if(x < 0 ) {
           return undefined;
       }
       for(var i = x; --i; ) {
           x *= i;
       }
       return x;
}
Run Code Online (Sandbox Code Playgroud)


Jav*_*ram 5

使用循环易于实现

function fact(num)
{
    if(num<0)
     return "Undefined";
    var fact=1;
    for(var i=num;i>1;i--)
      fact*=i;
    return fact;
 }

<input type="button" value="Find factiorial" onclick="alert(fact(6))">
Run Code Online (Sandbox Code Playgroud)


nig*_*are 5

function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

alert( factorial(5) );
Run Code Online (Sandbox Code Playgroud)

您可以尝试使用递归方法