我是Java语言的新手,并且正在关注freecodecamp。据我了解,我认为每次for循环中的数字乘以i本身的值,我就应该能够将其乘以i。我这样做是因为我试图分解。我有点偷窥的答案,他们使用了分解类型的javascript函数之类的东西。我仍然想使用自己的编码来解决这个问题。我该怎么办?
下面是我已经尝试过的代码。
function factorialize(num) {
for (let i = 1; i < num; i++) {
let answer = i * num;
}
return answer;
}
如果我为数字输入10,我希望它取10的阶乘(即10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1)。我希望它也能以0起作用,但是我们总是可以从我最初的问题开始。
答案 0 :(得分:5)
您需要在循环之前声明和初始化answer
,并且需要使用i
和answer
进行乘法。
在您已经以1
作为起始值的同时,您可以从第二个值开始循环。而且您还需要最后一个值。
值得一读:What's the difference between using "let" and "var"?
function factorialize(num) {
let answer = 1;
for (let i = 2; i <= num; i++) {
answer = i * answer;
}
return answer;
}
console.log(factorialize(5));
while循环方法
function factorialize(num) {
var product = 1;
while (num) product *= num--;
return product;
}
console.log(factorialize(5));
一种递归方法。
function factorialize(num) {
return num
? num * factorialize(num - 1)
: 1;
}
console.log(factorialize(5));
答案 1 :(得分:1)
您也可以始终使用while
循环:
function factorialize(num)
{
let answer = 1;
while (num > 0)
{
answer = answer * num;
num--;
}
return answer;
}
console.log("Result for 0:", factorialize(0));
console.log("Result for 5:", factorialize(5));
console.log("Result for 10:", factorialize(10));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
或者采用递归方式:
const factorialize = (num) => num <= 0 ? 1 : num * factorialize(num - 1);
console.log("Result for 0:", factorialize(0));
console.log("Result for 5:", factorialize(5));
console.log("Result for 10:", factorialize(10));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}