Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree 100% with shog9's answer - with the algorithm you used to calculate Fibonacci, you have to be really careful with floating point values. I found that the page <a href="http://cubbi.com/fibonacci/c++.html" rel="nofollow noreferrer" title="cubbi.com: fibonacci numbers in c++">cubbi.com: fibonacci numbers in c++</a> seems to show other ways of obtaining them.</p> <p>I looked around for a good idea on how to make your implementation of GenerateNthFibonacciNumber handle cases where it returns the double 54.999999, but when you cast to an int or a long you get 54.</p> <p>I came across what appears to be a reasonable solution at <a href="http://www.codingforums.com/archive/index.php/t-10827.html" rel="nofollow noreferrer" title="C++ Rounding">C++ Rounding</a>, which I have adapted below in your code.</p> <p>Also, It's not a <strong>huge</strong> deal, but you may want to precalculate PHI, then either pass it as a parameter or reference it as a global - now you are recalculating it every time you call the function.</p> <pre><code>double GenerateNthFibonacciNumber(const int n) { //This generates the nth Fibonacci Number using Binet's Formula const double PHI = (1.0 + sqrt(5.0)) / 2.0; double x = ((pow(PHI,n)-pow(-1.0/PHI,n)) / sqrt(5.0)); // inspired by http://www.codingforums.com/archive/index.php/t-10827.html return ((x - floor(x)) &gt;= 0.5) ? ceil(x) : floor(x); } </code></pre> <p>Finally, here's how I rewrote your Solve() method so that GenerateNthFibonacciNumber(FibIndex) is only called in one place in the code. I also added the column with the current running total of the even Fibonacci terms to your output:</p> <pre><code>double Solve() { long FibIndex = 0; double result = 0.0; double oldresult = 0.0; int done = 0; const double PHI = (1.0 + sqrt(5.0)) / 2.0; while (!done) { double currentFib = GenerateNthFibonacciNumber(++FibIndex); if ((int)currentFib % 2 == 0) { oldresult = result; if (currentFib &gt;= 4000000.0) { done = 1; } else { result += currentFib; } } cout &lt;&lt; currentFib &lt;&lt; " " &lt;&lt; (int)currentFib &lt;&lt; " " &lt;&lt; (int)currentFib % 2 &lt;&lt; " " &lt;&lt; (int)result &lt;&lt; "\n"; } return result; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload