weird problem!

This is a discussion on weird problem! within the C Programming forums, part of the General Programming Boards category; i have a very weird problem with a float. i've read from a file a number: 423.230000 if i: Code: ...

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    167

    weird problem!

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

    423.230000

    if i:
    Code:
    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:
    Code:
    tmp[*n].val+=x;
    printf("%f ",tmp[*n].val);
    it prints me:
    423.230011
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    > 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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    167
    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 Cprogramming.com
    Replies: 8
    Last Post: 01-11-2006, 11:05 PM
  3. Really Weird itoa Problem
    By Grantyt3 in forum C++ Programming
    Replies: 8
    Last Post: 12-19-2005, 11:44 PM
  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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21