如何将此 JavaScript 递归函数转换为迭代函数?

欧玛

如何将此递归函数更改为迭代函数?我正在学习 JavaScript 并希望将此练习作为练习。

function squirt(n, g) {
  if (!g) {
    // Take an initial guess at the square root
    g = n / 2.0;
  }

  var d = n / g; // Divide our guess into the number
  var ng = (d + g) / 2.0; // Use average of g and d as our new guess

  if (g == ng) {          
    // The new guess is the same as the old guess; further guesses
    // can get no more accurate so we return this guess
    return g;
  }

  // Recursively solve for closer and closer approximations of the square root
  return squirt(n, ng);
}
gurvinder372

您可以使用while循环并使用递归退出条件作为循环退出条件while

function squirt( n, g ) 
{   
  var d, ng, g = n / 2.0; //initialize g
  while ( g != ( d + g ) / 2.0 ) //convert g==ng to this
  {
     d = n / g; 
     g = ( d + g ) / 2.0;     
  }

  return g; //return g
}

演示

function squirt( n, g ) 
{   
  var d, ng, g = n/2.0;
  while ( g != ( d + g ) / 2.0 )
  {
     d = n / g; 
     g = ( d + g ) / 2.0;     
  }
  return g;
}

console.log( squirt(4) );
console.log( squirt(5) );
console.log( squirt(6) );
console.log( squirt(7) );
console.log( squirt(8) );
console.log( squirt(9) );
console.log( squirt(10) );

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章