如何获得一个JavaScript析因程序循环来显示所使用的工作? [英] How to get a JavaScript factorial programs' loop to show the working used?
问题描述
您好,尽管我不太了解它,但我仍然面临用JavaScript编写程序的挑战,该程序会要求用户输入数字,然后计算该数字的阶乘.我使用已经问过的问题并设法使计算正常进行,但无法获得所需的输出.我必须在以下输出中获取它,而不使用任何奇特的库或额外的变量/数组(我想不出怎么做):
Hello there I have been challenged to write a program in JavaScript despite not really knowing much about it that asks the user for a number and then calculates the factorial of that number. I used already asked questions and managed to get the calculation to work but couldn't get the required output. I have to get it in the following output without using any fancy libraries or extra variables/arrays (which I can't think of how to do) :
(假设用户输入为5):
(assuming user input is 5):
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
这是到目前为止我得到的代码:
Here is the code I've got so far:
//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 + ".");
}
我知道周围有很多类似的问题,并使用它们来帮助我进一步理解,但这是将输出转换为我正在努力使用的必需格式.有人告诉我有可能发生循环,但不知道从哪里开始实施,只能使用该解决方案.
I know there are many similar questions to this as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but don't know where to begin implementing that and I'm only allowed to use that solution.
不幸的是,这是挑战中较大程序的一部分,我只能使用以下变量:
Unfortunately this is part of a larger program in the challenge and I can only use the following variables:
数字(变量初始化为0以容纳用户输入)阶乘(变量初始化为1以保存计算的阶乘的值)计数(可变以保持执行循环以执行阶乘计算的次数)
Number (variable initialised as 0 to hold user input) Factorial (variable initialised to 1 to hold value of calculated factorial) Count (variable to hold number of times loop is executed for performing factorial calculation)
推荐答案
可能您只需要在该循环中构建一个字符串即可(在计算实际值的基础上):
Probably you just need to build a string in that loop (on top of calculating the actual value):
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);
"no-array子句"在您的任务中大概意味着您不应该构建一个数组并在其上使用 join()
,例如
The "no-array clause" in your task presumably means that you are not supposed to build an array and use join()
on it, like
let arr=[1,2,3,4,5];
console.log(arr.join("*"));
这篇关于如何获得一个JavaScript析因程序循环来显示所使用的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!