简体   繁体   中英

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.

How can I stop i reaching 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

should be 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

and just do this change: 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 -- .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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