Thread: Very simple printf

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

    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,909
    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 06:17 PM.

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    113
    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,834
    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, 10:25 AM
  2. Newb Help: Full Arrays and Functions
    By LycanGalen in forum C Programming
    Replies: 5
    Last Post: 01-31-2008, 08: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, 01:32 PM
  4. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  5. Double to Int conversion warning
    By wiznant in forum C Programming
    Replies: 15
    Last Post: 09-19-2005, 09:25 PM