Thread: Issue with typecasting float to int

  1. #1
    Registered User
    Join Date
    Oct 2020
    Posts
    69

    Issue with typecasting float to int

    Code:
    #include <stdio.h>
    
    
    int main()
    {
        int i = 0;
        for(i = 0; i <= 10; i++)
        {
            float offset = (i/1000)*256;
            printf("%d\n", (int)(offset));
        }
        return 0;
    }
    Output:
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    Expected Output:
    0
    0
    0
    0
    1
    1
    1
    1
    2
    2
    2

    Could you explain why this is happening?

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    888
    Code:
    float offset = ( i / 1000 ) * 256;
    i is an int, 1000 is an int, 256 is an int...

    i/1000 = 0 (int)
    0 * 256 = 0 (int)
    After this sub-expression 0 is converted to float (0.0f)...

    If you want a floating point calculation of 1/1000 you should use ONE of the terms (dividend or divisor) as a float:
    Code:
    float offset = ( i / 1000.0f ) * 256;
    This will promote i to float, and the result of i / 1000.0f will be a float, which will promote 256 to a float as well:
    Code:
    #include <stdio.h>
    
    
    int main()
    {
      int i;
    
      for ( i = 0; i <= 10; i++ )
      {
        // NOTE: dividing by 1000.0f will promote i and 256 to float.
        float offset = ( i / 1000.0f ) * 256;
    
        printf ( "%d\n", ( int )offset );
      }
    
      return 0;
    }
    Last edited by flp1969; 03-06-2021 at 10:23 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Float data type issue
    By Figen in forum C Programming
    Replies: 2
    Last Post: 01-31-2011, 01:42 PM
  2. Puzzling issue... Is typecasting the answer?
    By mike1305 in forum C Programming
    Replies: 6
    Last Post: 05-16-2010, 07:38 PM
  3. float/int issue if converting C to F
    By XodoX in forum C++ Programming
    Replies: 13
    Last Post: 02-16-2009, 02:03 AM
  4. float calculation issue
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 05-26-2008, 04:56 AM
  5. Possible Issue with Float?
    By nate92488 in forum C Programming
    Replies: 8
    Last Post: 04-25-2007, 12:38 PM

Tags for this Thread