title: Getting an infinite loop in Babylonian Algorithm for square roots in C++
body: <p>I have thoroughly searched for this topic all over the internet, and the threads are either dead, or use a different method than what is described in my book.</p>
  <p>For example, <a href="http://www.geeksforgeeks.org/square-root-of-a-perfect-square/" rel="nofollow noreferrer">http://www.geeksforgeeks.org/square-root-of-a-perfect-square/</a> . This doesn't work for me because my algorithm needs to loop until it reaches 1% of the last &quot;guess&quot;.</p>
  <p>Here is the question from the text.</p>
  <blockquote>
  <p>The Babylonian algorithm to compute the square root of a number n is as follows:</p>
  <ol>
  <li>Make a guess at the number (you can pick n/2 as your initial guess).</li>
  <li>Compute r = n / guess</li>
  <li>Set guess = (guess + r) / 2</li>
  <li>Go back to step 2 for as many iterations as necessary. The more that steps 2 and 3 are repeated, the closer guess will become to the
  square root of n.</li>
  </ol>
  <p>Write a program that inputs an integer for n, iterates through the
  Babylonian algorithm until guess is within 1% of the previous guess,
  and outputs the answer as a double.</p>
  </blockquote>
  <p>I have written the following code:</p>
  <pre><code>#include &lt;iostream&gt;
  
  using std::cout;
  using std::cin;
  using std::endl;
  
  int main()
  {
  int  n;
  double r, guess(4), lastGuess;
  
  cout &lt;&lt; &quot;Enter a number to find the square root of: &quot;;
  cin &gt;&gt; n;
  
  do
  {
  
      r = n / guess;
      lastGuess = guess;
      guess = ( guess + r ) / 2;
  
  //  cout &lt;&lt;&quot;Guess: &quot; &lt;&lt; guess &lt;&lt; endl;
  //  cout &lt;&lt;&quot;Last Guess: &quot; &lt;&lt; lastGuess &lt;&lt; endl;
  
      cout &lt;&lt; &quot;Guess : &quot; &lt;&lt; guess  &lt;&lt; endl;
      cout &lt;&lt; &quot;Last Guess 1% = &quot; &lt;&lt; lastGuess + ( lastGuess * 0.01 ) &lt;&lt; endl;
      cout &lt;&lt; &quot;r = &quot; &lt;&lt; r &lt;&lt; endl;
  
  } while( guess &gt;= lastGuess * 0.01 );
  cout &lt;&lt; r;
  
  return 0;
  }
  </code></pre>
  <p>The program computes the right answer for r, but the loop doesn't terminate despite guess being greater than 1% added to lastGuess.</p>
  <p>This program produces the following output when inputting 144 as n.</p>
  <pre><code>....
  r = 12
  Guess : 12
  Last Guess 1% = 12.12
  r = 12
  Guess : 12
  Last Guess 1% = 12.12
  r = 12
  Guess : 12
  Last Guess 1% = 12.12
  r = 12
  Guess : 12
  Last Guess 1% = 12.12
  ....
  </code></pre>
  <p>The root (r) is correct (12). The guess is LESS than lastGuess (12 &lt; 12.12), which should return a false to the condition, correct?. Why is the loop not ending?</p>