简体   繁体   English

使用JavaScript中的循环查找阶乘

[英]Finding the factorial using a loop in javascript

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 = inputNumber the 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);

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); 

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);
var inputNumber = prompt('Please enter an integer');
var total = 1;

for (i = 0; i < inputNumber; i++){
    total = total * (inputNumber - i);
}

alert(inputNumber + '! = ' + total);

You could use the input value and a while statement with a prefix decrement operator -- . 您可以将输入值和while语句与前缀减量运算符--

 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); 

Using total *= i; 使用总计* = 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: 这将很好地工作:

var inputNum = prompt("please enter and integer");
var total = 1;
for(i = inputNum; i > 1; i--){
 total *= i;
}
console.log(total);

 function factorialize(num) { var result = num; if(num ===0 || num===1){ return 1; } while(num > 1){ num--; result =num*result; } return result; } factorialize(5); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM