如何使用、do loop、while loop计算用户在Javascript中输入的数字的阶乘?
我上一个问题的快速跟进问题。我想在下面添加代码,以计算用户在Javascript中输入的数字的阶乘如何使用、do loop、while loop计算用户在Javascript中输入的数字的阶乘?,javascript,while-loop,do-loops,Javascript,While Loop,Do Loops,我上一个问题的快速跟进问题。我想在下面添加代码,以计算用户在Javascript中输入的数字的阶乘 <!DOCTYPE html> <html> <head> <title>Sum of Numbers</title> <script> var numbers = prompt("Enter a number 1-100"); while (numbers!=null &&
<!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>
数之和
变量编号=提示(“输入编号1-100”);
(数)=NULL &(iSnAn(PARSETIN(数字))>PARSETIN(数字)>100πPARSETIN(数字)< P >如果你试图总结数字,考虑使用算术级数公式。如果你想得到阶乘,则方法如下所示。
如果要使用循环求和,只需将*=
更改为+=
While循环方法
边走边做
这应该可以奏效
也许还可以考虑检查边缘情况,比如n是否为负值
祝你好运。
< P>如果你试图总结数字,考虑使用算术级数公式。如果你想得到阶乘,那么方法如下所示。
如果要使用循环求和,只需将*=
更改为+=
While循环方法
边走边做
这应该可以奏效
也许还可以考虑检查边缘情况,比如n是否为负值
祝你好运。While Loop:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
const-fact=n=>
{
如果(n)
{
如果(n)
{
设r=1
而(n)r*=n--
返回r
}
让numValue=parseInt(window.prompt(msgPrompt_1',),10)
而(isNaN(numValue)| | numValue>100 | | numValue<0)
{
numValue=parseInt(window.prompt(msgPrompt_n',),10)
}
警报(`factorial value of${numValue}为=${fact(numValue)}`)
While循环:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
const-fact=n=>
{
如果(n)
{
如果(n)
{
设r=1
而(n)r*=n--
返回r
}
让numValue=parseInt(window.prompt(msgPrompt_1',),10)
而(isNaN(numValue)| | numValue>100 | | numValue<0)
{
numValue=parseInt(window.prompt(msgPrompt_n',),10)
}
警报(`factorial value of${numValue}is=${fact(numValue)}`)
0
不是边缘案例:0!=1
。感谢您指出。我更新了答案描述。
0不是边缘案例:0!=1
。感谢您指出这一点。我更新了答案描述。:)
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
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;
}