簡體   English   中英

Javascript Factorize 返回不正確的結果

[英]Javascript Factorialize returns incorrect result

只是想知道是否有人能告訴我為什么這會返回 100 而不是 120? 它應該計算因子的總數。

function factorialize(num) {

  for(var i = 1; i <= num; i++ ) {
    var fact = i+i;    
    total = fact * fact;
  }
  return total;
}

factorialize(5);

這不是計算階乘的正確方法。 您的代碼中發生的事情是,最后一次行total = fact * fact; 運行時, fact的值為 10(因為i是 5),因此 10 * 10 變為 100,這就是它返回的值。

TLDR 是您覆蓋了fact所有值。 var的作用域是 JS 中的一個函數。 最終你達到i = 5 ,最終將 fact 設置為(5+5) * (5+5) ,即 100。

如果您要計算階乘,請使用以下代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM