Thread: help with simple type casting problem

  1. #1
    Jeremy_S
    Guest

    help with simple type casting problem

    Can someone help me with this type casting problem? I've tried to simplify it as much as possible.

    For example:
    int rd, width
    float scd, blw;


    rd=7;
    width=10;
    blw = (float) rd/width;
    scd = (int) blw*100;

    blw equals 0.7000 according to the program.
    scd should equal 70 but the program returns 69.

    Any suggestions?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Try changing the code that assigns the value to scd to have parenthesis around the multiplication operation like so and see if that works.
    Code:
    scd = (int) (blw*100);
    Incidentally when I tried the code as you provided, I got 0.7 for blw and 0 for scd, not 69.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    floats are approximations (and doubles are more accurate approximations)

    Which means you can't just arbitrarily write a mathematical expression and expect to get the same computational answer.

    The fact of the matter is, your intermediate answer is 69.99999, but the cast to integer simply truncates the number, no matter how close to 70 it happens to be.

    Because the low order bits are lost whenever you store a float (and to a lesser extent when you store a double), these can produce different answers

    blw = (float) rd/width;
    scd = (int) blw*100;

    And
    scd = (int) ((float) rd/width)*100;


    http://www.cprogramming.com/cboard/s...loat#post69676

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 08:57 AM
  4. Erros in Utility Header File
    By silk.odyssey in forum C++ Programming
    Replies: 4
    Last Post: 12-22-2003, 06:17 AM
  5. static casting problem
    By rxg00u in forum C++ Programming
    Replies: 4
    Last Post: 04-24-2002, 07:13 PM