title: C (C++, Objective-C) typecast from float to int results in decremented int
body: <p>I've written an iPhone-App and encountered a problem concerning typecasting between float and int. I've rewritten the code in C and the results always were the same, no matter if having it compiled under OS X (Console and Xcode), Linux (Console) or Windows (Visual Studio):</p>
  
  <pre><code>// Calculation of a page index depending on the amount of pages, its x-offset on the view
  // and the total width of the view
  #include &lt;stdio.h&gt;
  
  int main()
  {
      int   result   = 0;
      int   pagesCnt = 23;
      float offsetX  = 2142.0f;
      float width    = 7038.0f;
  
      offsetX = offsetX / width;
      offsetX = (float)pagesCnt * offsetX;
      result  = (int)offsetX;
  
      printf("%f (%d)\n", offsetX, result);
      // The console should show "7.000000 (7)" now
      // But actually I read "7.000000 (6)"
  
      return 0;
  }
  </code></pre>
  
  <p>Of course, we have a loss of precision here. When doing the math with the calculator x results in 7.00000000000008 and not in just 7.000000. </p>
  
  <p>Nevertheless, as much as I understand C, this shouldn't be a problem as C is meant to truncate the the after-point-positions of a floating point number when converting it to an integer. In this case this is what I want actually.</p>
  
  <p>When using double instead of float, the result would be as expected, but I don't need double precision here and it shouldn't make any difference.</p>
  
  <p>Am I getting something wrong here? Are there situations when I should avoid conversion to int by using (int)? Why is C decrementing result anyway? Am I supposed to always use double?</p>
  
  <p>Thanks a lot!</p>
  
  <p>Edit: I've misformulated something: Of course, it makes a difference when using double instead of float. I meant, that it shouldn't make a difference to (int) 7.000000f or 7.00000000000008.</p>
  
  <p>Edit 2: Thanks to you I understand my mistake now. Using printf() without defining the floating point precision was wrong. (int)ing 6.99... to 6 is correct, of course. So, I'll use double in the future when encountering problems like this.</p>