Javascript 在javascript中使用循环查找阶乘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43708479/
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
Finding the factorial using a loop in javascript
提问by who's.asking
I need to use a loop to find the factorial of a given number. Obviously what I have written below will not work because when i = inputNumberthe equation will equal 0.
我需要使用循环来查找给定数字的阶乘。显然,我在下面写的内容将不起作用,因为i = inputNumber等式何时等于 0。
How can I stop i reaching inputNumber?
我怎样才能阻止我到达 inputNumber?
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i <= inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
回答by Zhenya Telegin
here is an error i <= inputNumber
这是一个错误 i <= inputNumber
should be i < inputNumber
应该 i < inputNumber
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
console.log(inputNumber + '! = ' + total);
回答by Islam Sayed
you can keep this: i <= inputNumber
你可以保留这个: i <= inputNumber
and just do this change: total = total * i;
只需进行此更改: total = total * i;
then the code snippet would look like this:
那么代码片段将如下所示:
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 1; i <= inputNumber; ++i){
total = total * i;
}
console.log(inputNumber + '! = ' + total);
回答by Carla
Using total *= i; will set up all of your factorial math without the need of extra code. Also, for proper factorial, you'd want to count down from your input number instead of increasing. This would work nicely:
使用总计 *= i; 将设置您所有的阶乘数学,而无需额外的代码。此外,对于适当的阶乘,您需要从输入数字开始倒计时而不是增加。这会很好地工作:
var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
total *= i;
}
console.log(total);
回答by bboy
var inputNumber = prompt('Please enter an integer');
var total = 1;
for (i = 0; i < inputNumber; i++){
total = total * (inputNumber - i);
}
alert(inputNumber + '! = ' + total);
回答by Nina Scholz
You could use the input value and a whilestatementwith a prefix decrement operator --.
var inputNumber = +prompt('Please enter an integer'),
value = inputNumber,
total = inputNumber;
while (--value) { // use value for decrement and checking
total *= value; // multiply with value and assign to value
}
console.log(inputNumber + '! = ' + total);
回答by Ogundeji Yusuff
function factorialize(num) {
var result = num;
if(num ===0 || num===1){
return 1;
}
while(num > 1){
num--;
result =num*result;
}
return result;
}
factorialize(5);

