Thread: printf a floating number (more complicated, please read topic)

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    23

    printf a floating number (more complicated, please read topic)

    I'm beginner to programming in general.

    Say I have:
    int x = 80;
    int y = 6;
    double average;

    average = x / y;

    printf("%f", average);

    when i do this it outputs 13.000000 but i need it to output 13.33333
    how would i go about doing this? i cannot change x or y to a double variable for it messes up other parts of my program. thanks in advance.

  2. #2
    Just a pushpin. bernt's Avatar
    Join Date
    May 2009
    Posts
    426
    Here, "x / y" is casted to double *after* the calculation x/y has been made.

    Explicitly casting to double before the calculation:
    Code:
    average = ((double) x) / ((double) y);
    will get you the expected floating-point result.
    Consider this post signed

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    161
    You would 'Type Cast' x or y. It will not change x or y.

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    You only need to typecast the first one:

    Code:
    double average = (double) x / y;
    @OP - use CODE tags in the future for posting.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by memcpy View Post
    You only need to typecast the first one:
    Well you can actually cast either one. As long as one of the operands is a double then the other must also be promoted to a double.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Big Floating Number, 100! Not right.
    By KAUFMANN in forum C Programming
    Replies: 7
    Last Post: 01-19-2011, 07:48 PM
  2. floating point number printf/string formating
    By stanlvw in forum C++ Programming
    Replies: 2
    Last Post: 04-22-2009, 04:41 PM
  3. how to read a digit of a floating point number?????
    By spicy_centipede in forum C Programming
    Replies: 15
    Last Post: 07-14-2007, 11:43 AM
  4. Floating point number
    By Mckooy in forum C Programming
    Replies: 1
    Last Post: 01-15-2006, 07:28 AM
  5. floating and double number
    By kashifk in forum C++ Programming
    Replies: 2
    Last Post: 05-09-2003, 09:52 PM