首页 > 解决方案 > 如何获得 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 + ".");
}

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

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

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

标签: javascriptfactorial

解决方案


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

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("*"));


推荐阅读