Very simple printf

This is a discussion on Very simple printf within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> int main(void) { float x=123.23f; printf("%f",x); return 0; } This code gives me the result 123.230003 Why ...

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    93

    Very simple printf

    Code:
    #include <stdio.h>
    
    int main(void)
    {
    float x=123.23f;
    printf("%f",x);
    return 0;
    }
    This code gives me the result 123.230003

    Why do I see the 3 at the end?

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,566
    Why are floating point calculations so..inaccurate?

    EDIT:
    Note that the "%f" with no precision specifiers gives you 6 digits after the decimal point, which for a float is enough to give you the bogus 3 out there. You could use a double to push the inaccuracy farther out right and have it not show up with the default "%lf" (you need the l in there for a double), but it's still not exact. Also, you can change printf to give less after the decimal point. For example, "%.3f" would give only 3 digits after the decimal.
    Last edited by anduril462; 02-17-2011 at 05:17 PM.

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    93
    Thanks for your perfect answer

    Code:
    #include <stdio.h>
    
    int main()
    {
    double x=123.23;
    printf("%lf\n",x);
    return 0;
    }
    This one gave the result:123.230000

    I firstly thought I had a mistake but after your reply I see there is an interesting area to discover. I will try to get some knowledge about binary representation of floating-point constants.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,832
    Understanding floating point is one of the more interesting things, and most misunderstood. It could get very deep mathematically as well. But as for how floating point is represented internally, it's worthwhile looking into it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-05-2009, 09:25 AM
  2. Newb Help: Full Arrays and Functions
    By LycanGalen in forum C Programming
    Replies: 5
    Last Post: 01-31-2008, 07:35 PM
  3. menu problem!!! need U R G E N T help!!!
    By catcat28 in forum C Programming
    Replies: 16
    Last Post: 11-19-2007, 12:32 PM
  4. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 04:42 PM
  5. Double to Int conversion warning
    By wiznant in forum C Programming
    Replies: 15
    Last Post: 09-19-2005, 09:25 PM

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