[英]How to calculate the factorial of a number entered by user in Javascript, using, do-loop, while-loop?
Quick follow-up question on my previous question.我之前的问题的快速跟进问题。 I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.我想将代码添加到以下代码以计算用户在 Javascript 中输入的数字的阶乘。
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
}
while (counter<=numOfLoops)
alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
If you are trying to sum up the numbers, consider using arithmetic series formula.如果您要对数字求和,请考虑使用算术级数公式。 If you're trying to get the factorial, the approach is shown below.如果您试图获得阶乘,则该方法如下所示。
If you want to sum using the loop, just change the *=
to +=
.如果您想使用循环求和,只需将*=
更改为+=
。
const fact = (n) => {
let res = 1;
while (n > 0) {
res *= n;
n--;
}
return res;
}
fact(5) // 120
const fact = (n) => {
let res = 1;
do {
res *= n;
n--;
} while (n > 0)
return res;
}
fact(3) // 6
That should do the trick.这应该够了吧。 :) :)
Maybe also considering checking for edge cases like if the n is negative.也许还考虑检查边缘情况,例如 n 是否为负。
Good luck.祝你好运。
While Loop: While循环:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
Do While:做时:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
do r *= n || 1 // in case of n == 0
while (n--)
return r;
}
complete code完整代码
const msgPrompt_1 = 'Please enter a number from 0 to 100', msgPrompt_n = 'Try again.... Enter a number 0-100', fact = n => { let r = 1 while(n) r *= n-- return r } let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10) while(isNaN(numValue) || numValue > 100 || numValue < 0) { numValue = parseInt(window.prompt(msgPrompt_n, ''), 10) } alert(`factorial value of ${numValue} is = ${fact(numValue)}` )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.