一个数的阶乘 [英] factorial of a number

查看:148
本文介绍了一个数的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code but it is not giving perfect result for factorial can u find it out 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>


推荐答案

你必须 return 该值。你去吧:

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

function run(number) {
    alert(fact(parseInt(number, 10)));
}

<input type="button" value="Find factiorial" onclick="run(txt1.value)">

(如何使其适用于我留给你的负数;)(但无论如何我在这篇文章中展示了))

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

Just for fun, a more correct, non recursive algorithm:

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

这篇关于一个数的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆