如何让 JavaScript 阶乘程序的循环显示使用的工作?



你好,我一直在挑战用JavaScript编写一个程序,尽管我对它了解不多,它会向用户询问一个数字,然后计算该数字的阶乘。我使用了已经提出的问题,并设法使计算工作,但无法获得所需的输出。我必须在以下输出中获得它,而不使用任何花哨的库或额外的变量/数组(我想不出该怎么做(:

(假设用户输入为5(:

The factorial of 5 is 5*4*3*2*1=120 
OR
5! is  5*4*3*2*1=120 

这是我目前掌握的代码:

//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number)) {
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0) {
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}

我知道有很多类似的问题,因为我环顾四周,并用它们来帮助我走到这一步,但我正在努力将输出转换为所需的格式。我被告知使用循环是可能的,但不知道从哪里开始实现,我只被允许使用该解决方案。

不幸的是,这是挑战中一个更大程序的一部分,我只能使用以下变量:

数字(变量初始化为0以保存用户输入(阶乘(变量初始化为1以保持计算阶乘的值(计数(变量用于保存执行阶乘计算的循环次数(

您可能只需要在该循环中构建一个字符串(在计算实际值的基础上(:

let input=parseInt(prompt("Number?"));
let output="";
let result=1;
for(let i=input;i>1;i--){
result*=i;
output+=i+"*";
}
console.log(input+"! is "+output+"1="+result);

";无数组子句";在您的任务中,大概意味着您不应该像一样构建阵列并在其上使用join()

let arr=[1,2,3,4,5];
console.log(arr.join("*"));

我主要在这里更新了您的代码,还请确保您在代码中使用相同的变量num,而不是number:

let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}

//prompts the user for a positive number
var num = parseInt(prompt("Please enter a positive number"));
console.log(num);
//checks the number to see if it is a string
if (isNaN(num))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (num < 0) 
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorials = [];
let result = 1;
for (count = num; count >= 1; count--) {
result *=count;
factorials.push(count);
}

//Sends the inital number back to the user and tells them the factorial of that number
alert("The " + num + "! is " + factorials.join('*') + " is " + result + ".");
}

最新更新