[英]Javascript Factorialize returns incorrect result
Just wondering if anyone can tell me why this returns 100 and not 120?只是想知道是否有人能告诉我为什么这会返回 100 而不是 120? It should calculate the total number of the factor.
它应该计算因子的总数。
function factorialize(num) {
for(var i = 1; i <= num; i++ ) {
var fact = i+i;
total = fact * fact;
}
return total;
}
factorialize(5);
This is not the correct way to calculate the factorial.这不是计算阶乘的正确方法。 What is happening in your code is, the last time the line
total = fact * fact;
您的代码中发生的事情是,最后一次行
total = fact * fact;
is run, fact
has a value of 10 (because i
is 5), so 10 * 10 becomes 100 and that is what it returns.运行时,
fact
的值为 10(因为i
是 5),因此 10 * 10 变为 100,这就是它返回的值。
TLDR is you're overwriting all the values of fact
. TLDR 是您覆盖了
fact
所有值。 var
is scoped to a function in JS. var
的作用域是 JS 中的一个函数。 Eventually you reach i = 5
, which eventually sets fact to (5+5) * (5+5)
which is 100.最终你达到
i = 5
,最终将 fact 设置为(5+5) * (5+5)
,即 100。
If you are trying to calculate the factorial, use this code:如果您要计算阶乘,请使用以下代码:
function factorialize(num) {
var total = 1; // Initialize the total. 0! = 1.
for(var i = 1; i <= num; i++ ) {
total = total * i; // Add the current index to the factors by multiplying it by the current total.
}
return total;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.