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

时间:2017-12-21 07:02:05

标签: javascript recursion

如何将此递归函数更改为迭代函数?我正在学习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);
}

1 个答案:

答案 0 :(得分:-2)

您可以使用const GrayScreen = (props) => { return ( <View style={styles.container}> <Text style={styles.welcome} onPress={() => Actions.black()}>{props.text}</Text> </View> ) } 循环并使用递归的退出条件作为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
}