Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does (int)55 == 54 in C++?
    primarykey
    data
    text
    <p>So I'm learning C++. I've got my "C++ Programming Language" and "Effective C++" out and I'm running through Project Euler. Problem 1...dunzo. Problem 2...not so much. I'm working in VS2008 on a Win32 Console App.</p> <p>Whats the Sum of all even terms of the Fibonacci Sequence under 4 million? </p> <p>It wasn't working so I cut down to a test case of 100...</p> <p>Here's what I wrote...</p> <pre><code>// Problem2.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { cout &lt;&lt; "Project Euler Problem 2:\n\n"; cout &lt;&lt; "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n\n"; cout &lt;&lt; "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n"; cout &lt;&lt; "Find the sum of all the even-valued terms in the sequence which do not exceed four million.\n\n"; cout &lt;&lt; "Answer: " &lt;&lt; Solve(); } double Solve() { int FibIndex = 0; double result = 0.0; double currentFib = GenerateNthFibonacciNumber(FibIndex); while (currentFib &lt; 100.0){ cout &lt;&lt; currentFib &lt;&lt; " " &lt;&lt; (int)currentFib &lt;&lt; " " &lt;&lt; (int)currentFib % 2 &lt;&lt; "\n"; if ((int)currentFib % 2 == 0){ result += currentFib; cout&lt;&lt;(int)currentFib; } currentFib = GenerateNthFibonacciNumber(++FibIndex); } return result; } 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; return ((pow(PHI,n)-pow(-1.0/PHI,n)) / sqrt(5.0)); } </code></pre> <p>And here's the output...</p> <blockquote> <p>Project Euler Problem 2:</p> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>Find the sum of all the even-valued terms in the sequence which do not exceed four million.</p> <p>0 0 0 <br> 1 1 1 <br> 1 1 1 <br> 2 2 0<br> 3 3 1<br> 5 5 1<br> 8 8 0<br> 13 13 1<br> 21 21 1<br> 34 34 0<br> 55 54 0<br> 89 89 1<br> Answer: 99<br></p> </blockquote> <p>So I have three columns of debug code...the number returned from the generate function, (int)generatedNumber, and (int)generatedNumber % 2</p> <p>So on the 11th term we have</p> <p>55,54,0</p> <p>Why does (int)55 = 54?</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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