Javascript 一个数的阶乘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4438131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
factorial of a number
提问by Mihir
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>
回答by Felix Kling
You have to return
the value. Here you go:
你必须要return
值。干得好:
function fact(x) {
if(x==0) {
return 1;
}
return x * fact(x-1);
}
function run(number) {
alert(fact(parseInt(number, 10)));
}
and
和
<input type="button" value="Find factiorial" onclick="run(txt1.value)">
(How to make it work for negative numbers I leave up to you ;) (but I showed in this post anyway))
(如何让它对负数起作用,我留给你;)(但无论如何我在这篇文章中展示了))
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;
}
回答by Javed Akram
Use loop its easy to implement
使用循环很容易实现
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))">
回答by nightmare
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) );
You can try to use recursion method
您可以尝试使用递归方法
回答by Kobi
- Your function doesn't return anything, ever.
- What do you do when x is 0?
- Minor point - apart from
alert
, you don't really do anything with the returned value.
- 你的函数永远不会返回任何东西。
- 当 x 为 0 时你会做什么?
- 次要点 - 除了
alert
,您实际上并没有对返回的值做任何事情。
Try this instead, if you will (hover over the text):
试试这个,如果你愿意(将鼠标悬停在文本上):
if(x==0) return 1;
return x * fact(x-1);
if(x==0) return 1;
return x * fact(x-1);
Working example: http://jsbin.com/apuka3/2
工作示例:http: //jsbin.com/apuka3/2
回答by Flinsch
You need to have a return
in your function in the first place. ;)
您首先需要return
在您的功能中使用 a 。;)
回答by cssimsek
Here's a short recursive version:
这是一个简短的递归版本:
function doFact(n) {
return +!(+(n)) || doFact(n - 1) * n;
}
function factorialFromInput() {
var theInputVal = document.getElementsByTagName("input")[0].value;
var theContainer = document.getElementById("resultContainer");
theContainer.innerHTML = "" + doFact(Math.abs(theInputVal));
}
.wrapper>* {
line-height: 2em;
width: 30%;
}
#resultContainer {
border: outset grey;
min-height: 1.1em;
padding-left: 0.3em;
background-color: #eff0f1;
overflow: scroll;
}
<div class="wrapper">
<input type="text" id="valEntered">
<br>
<button onclick="factorialFromInput();">Calculate Factorial</button>
<br>
<div id="resultContainer"></div>
</div>
回答by Redu
Recursion in JS is open to stack overflow error and also very slow. Looping by other means is better. My contribution to factorial code would be a straightforward one;
JS 中的递归容易出现堆栈溢出错误,而且速度也很慢。通过其他方式循环更好。我对阶乘代码的贡献很简单;
var fact = n => n > 0 ? Array.from({length: n}, (_,i) => i+1)
.reduce((p,c) => p*c)
: 1;
console.log(fact(5));
回答by Jamshid Ajam
I wrote this and it works.
我写了这个并且它有效。
var d = 1;
for (num; num > 1; num--) {
d *= num;
}
return d;
回答by Srikrushna
function fact(n) {
if (n > 1) {
return n * fact(n-1);
} else {
return 1;
}
}
console.log(fact(5));
Using ternary operatorwe replace the above code in a single line of code as below
使用三元运算符,我们将上面的代码替换为一行代码,如下所示
function fact(n) {
return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));
回答by Bijay Pal
This is the very easiest way and latest JS(ES6)
这是最简单的方法和最新的 JS(ES6)
factorial = n => n - 1 > 0 ? n * factorial(n - 1) : n;
//output
console.log(factorial(5));
Here I used ES6 arrow function. For better understanding please see what is arrow function.
这里我使用了 ES6 箭头函数。为了更好地理解,请参阅什么是箭头函数。