我面临的挑战是用 JavaScript 编写一个程序,允许用户执行多项任务,其中之一是要求用户提供一个数字并计算该数字的阶乘,然后以需求中列出的格式显示它。由于我对 Java 脚本了解不多,所以我使用了已经提出的问题并设法使计算正常工作,但无法弄清楚如何在仍满足要求的情况下获得所需的输出。
要求: • 只能使用提供的变量 Number(初始化为 0 的变量,用于保存用户输入) Factorial(初始化为 1 的变量,用于保存计算的阶乘值) Count(用于保存执行阶乘计算的循环次数的变量)。这是挑战设置的限制,而不是我的限制。 • 无法使用精美的库。 • 需要对输出使用循环解决方案。另一篇文章的答案需要引入新的变量,也许是我缺乏理解,但也许自上一篇文章以来我获得的写得不好的伪代码可能会有所帮助。• 以以下格式输出:(这是一个警报,因此程序的一部分没问题)
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 + ".");
}
喵喵时光机
弑天下
随时随地看视频慕课网APP
相关分类