title: How to display precisely the decimal digits of a double in C++?
body: <blockquote>
    <p><strong>Problem</strong><br>
    Given two integers a, b, a &lt; b. Display its decimal expansion. You will print the decimal expansion of integer quotient given, stopping just as the expansion terminates or just as the repeating pattern is to repeat itself for the first time. If there is a repeating pattern, you will say how many of digits are in the repeating pattern.</p>
    
    <p><strong>Sample Input</strong><br>
    3 7<br>
    345 800<br>
    112 990<br>
    53 122   </p>
    
    <p><strong>Sample Output</strong><br>
    .428751<br>
    The last 6 digits repeat forever.<br>
    .43125<br>
    This expansion terminates.<br>
    .113<br>
    The last 2 digits repeat forever.<br>
    .4344262295081967213114754098360655737704918032786885245901639<br>
    The last 60 digits repeat forever.  </p>
  </blockquote>
  
  <p><em>Note: This problem is original from the ProgFest programming contest.</em></p>
  
  <p>The algorithm for this problem is not difficult if we apply these three theorems:
  <img src="https://i.stack.imgur.com/1s78c.png" alt="enter image description here"></p>
  
  <p>However, the problem that I'm facing is the rounding-off when calculating alpha using the recursive formula given in Theorem 1. The display function is defined as follows:</p>
  
  <pre><code>void displayFraction( int n, int d, int length ) {
      std::cout &lt;&lt; ".";
      double alpha = static_cast&lt;double&gt;( n ) / d;
      for( int i = 1; i &lt;= length; ++i ) {
          int c = std::floor( 10.0 * alpha );
          alpha = 10.0 * alpha - c;
          std::cout &lt;&lt; c;
      }
  }
  </code></pre>
  
  <p>And my output was:</p>
  
  <pre><code>.4344 2622 9508 1967 3732 7807 5683 6291 4025 7835 3881 8359 3750 0000 0000 0
  </code></pre>
  
  <p>where the problem output was:</p>
  
  <pre><code>.4344 2622 9508 1967 2131 1475 4098 3606 5573 7704 9180 3278 6885 2459 0163 9
  </code></pre>
  
  <p>As you can see, it was correct up to the 16th digit. So my question is, how I can prevent the truncating digits when performing the calculation in this particular situation? Any idea?</p>