繁体   English   中英

在 Javascript 中使用 while 循环对数字进行阶乘

[英]Factorial of a number using a while loop in Javascript

我需要帮助创建代码来查找数字的阶乘。 任务是

  1. 创建一个变量来存储您的答案并将其初始化为一个
  2. 创建一个在给定值下存在的循环,事实
  3. 检查事实是一还是零
  4. 将事实与您的答案变量相乘
  5. 在循环结束时减少事实
  6. 使用 console.log 打印答案

伪代码是

while(factorial)
  if factorial == 0 or factorial == 1
    break 
  result => result * factorial
  factorial  => factorial - 1

我下面的代码不完整,因为我对伪代码感到困惑。

function nth_fact(nth){
var a = 1
while(nth_fact)
if (nth_fact == 0 || nth_fact == 1){
    break;
result => result * nth_fact
nth_fact => nth - 1
console.log() 
}
}

首先让我们检查一下出了什么问题:

var a = 1

什么a ? 它绝对不是一个变量的好名字。 也许将其命名为result 这同样适用于应该命名为factorialnth和应该命名为factorize或 sth 的nth_fact 您还应该始终使用; 结束陈述。

while(nth_fact)

由于您的 while 循环包含多个语句( if和两个赋值),因此您需要在条件之后使用{在此处打开一个块。 nth_fact指的是函数,你宁愿在这里取factorial

 if (nth_fact == 0 || nth_fact == 1){
   break;

现在你为 if 打开一个块语句,但你永远不会关闭它。 所以休息后你需要另一个}

result => result * nth_fact
nth_fact => nth - 1
console.log() 

=>是箭头函数表达式,但您需要赋值运算符= 您还需要向console.log 传递一些东西,例如console.log(result)

全部一起:

 function factorize(factorial){
   var result = 1;
  while(factorial){
     if (factorial == 0 || factorial == 1){
        break;
     }
     // ?
     factorial = factorial - 1;
     console.log(result);
  }
  return result;
}

该伪代码确实令人困惑,因为它所谓的factorial实际上不是阶乘——它是当前值,结果(实际上是我们正在寻找的阶乘)乘以它。 另外, if是多余的,因为while已经检查了相同的条件。 所以正确的伪代码是

currentValue = argument
factorial = 1

while (currentValue > 1)
    factorial = factorial * currentValue
    currentValue = currentValue - 1

// now, 'factorial' is the factorial of the 'argument'

一旦你解决了这个问题,这是一个奖励任务:

  • 创建一个函数range(a, b) ,它创建一个从ab的数字数组。 例如, range(5, 8) => [5, 6, 7, 8]
  • 创建一个函数product(array)将数组元素彼此相乘。 例如, product([2, 3, 7]) => 42
  • 使用productrange编写阶乘函数

 function factorial(num) { var result = 1 while (num) { if ((num) == 0 || (num) == 1) { break; } else { result = result * num; num = num - 1; } } return `The factorial of ${val} is ${result}` } let val = prompt("Please Enter the number : ", "0"); var x = parseInt(val); console.log(factorial(x));

一个简短而干净的代码是:

 let number = 5; let numberFactorial = number; while(number > 1){ numberFactorial = numberFactorial * (number-1); number--; } console.log(numberFactorial);

我这样解决

 function factorial(number) { let num = 1; let result = 1; while (num <= number) { result = result * num; num++; } return result; } const myNumber = factorial(6); console.log(myNumber);

你使用了正确的方法。 只是语法错误。 这里是:

function nth_fact(nth){
var result = 1 ;
while(nth){
  if ((nth) == 0 || (nth) == 1)
    break ;
  result = result * nth;
  nth = nth - 1
 }
console.log(result); 
return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM