CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2000
    Location
    Seattle , WA
    Posts
    87

    Type conversion.

    --------------------------------------------------------------------------
    unsigned int x = 100;
    unsigned int y = 200;
    float f;

    f = (float)x-(float)y; // ok result -100.000

    f = (float)(x-y); // Not ok , result 4.29497e+009
    --------------------------------------------------------------------------
    can anybody tell me why this behaviour by compiler

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    The first method converts x to float , converts y to float,
    and does the subtraction using float arithmetic.

    The second does the subtraction using "unsigned int" arithmetic,
    and converts the result to float.

    You are getting a "negative" number for the unsigned int subtraction.

  3. #3
    Join Date
    Jan 2001
    Posts
    253
    You are getting an underflow when you subtract 200 from 100 as an unsigned int. Assuming a 32 bit integer, this results in a very large positive number (4294967196). You then cast this to a float, and get 4.29497e+009.

    This is the same as doing:
    unsigned int x = 100;
    unsigned int y= 200;

    unsigned int z = x - y; // this underflows
    float f = (float) z;


    When you put the float cast before each number, you are subtracting 2 floats. Since floats are a signed data type, they can handle going negative. This gives you the result that you are expecting.

    Best regards,
    John

  4. #4
    Join Date
    Mar 2000
    Location
    Seattle , WA
    Posts
    87
    Thanks guys

  5. #5
    Join Date
    Jun 2002
    Posts
    33
    While the answers above are absolutely correct, just for those who still don't understand, using the type:

    int x = 100;
    int y = 200;

    instead of:

    unsigned int x = 100;
    unsigned int y = 200;

    and then casting a conversion to float:

    float z = (float) (x-y);

    should produce the desired result (-100.0) since x and y can now handle the negative SIGNature.

    Alan.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured