Thread: weird problem!

  1. #1
    Registered User
    Join Date
    Dec 2005

    weird problem!

    i have a very weird problem with a float.
    i've read from a file a number:


    if i:
    printf("%f ",tmp[*n].val+x);
    it prints me:
    423.230000 that is ok!
    tmp[*n].val is a float component of a structure containing the integer (423.00000) and x is a float containing 0.230000

    but if i do:
    printf("%f ",tmp[*n].val);
    it prints me:
    Where does the 0.000011 comes from ?
    This problem occurs within a function!

    How can I fix it ?

    Thank you!
    Last edited by spank; 04-08-2006 at 02:01 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > printf("%f ",tmp[*n].val+x);
    Both get promoted to double, before the addition is performed and the result passed to printf

    > tmp[*n].val+=x;
    >printf("%f ",tmp[*n].val);
    The calculation is done using float, and it only becomes a double when you pass it to printf.

    > 423.230011
    floats have 6 decimal digits of precision, so you can only rely on 423.230
    The remainder of the result is random noise.

    The reason it works for doubles is they have about 15 decimal digits of precision.

    > How can I fix it ?
    Always use doubles unless you have a specific reason not to.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2005
    yep... that solved it. Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Weird Problem With Pointer
    By DarkDot in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2007, 07:50 PM
  2. Weird problem on '02 3.4L V6 auto
    By VirtualAce in forum A Brief History of
    Replies: 8
    Last Post: 01-12-2006, 12:05 AM
  3. Really Weird itoa Problem
    By Grantyt3 in forum C++ Programming
    Replies: 8
    Last Post: 12-20-2005, 12:44 AM
  4. Replies: 6
    Last Post: 05-12-2005, 03:39 AM
  5. Weird class problem!
    By aker_y3k in forum C++ Programming
    Replies: 2
    Last Post: 09-25-2002, 06:12 AM