Thread: Loss of Precision Question.

  1. #1
    Registered User
    Join Date
    Sep 2008

    Loss of Precision Question.

    Hey, Im having a bit of a problem printing this data.
    I am trying to divide two integers and print out a float.
    For example:

    sum = 521;
    printf(" a = %.1f\n", (float)(sum/2));
    printf(" b = %.2f\n", (float)(sum/100));
    I want to get:
    a = 260.5
    b = 5.21%

    but instead I get:
    a = 260.0
    b = 5.00

    Also , how do i get that percentage sign in there after the number?
    thanks alot.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    cast sum to a float, not the result (which is still being done in integer math).
    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
    Sep 2008
    Toronto, Canada
    Yeah, what he said.

    I assume sum is an int. So that means any calculations such as sum/2 are integer math including the result. You need to either declare sum as a float, or force it to be float prior to the division:
    (float)sum / 2
    or better still make the constant a floating point value:
    sum / 2.0
    Also, you said you wanted the output to look like b = 5.21%
    printf(" b = %.2f%%\n", ...
    NOTE the double '%' to print out a single '%'. That way it's not mistaken for another format specifier.
    Last edited by nonoob; 10-01-2008 at 05:42 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Precision based floating-point
    By Mario F. in forum C++ Programming
    Replies: 4
    Last Post: 07-17-2006, 10:35 AM
  2. time precision (ctime), tm struct question
    By cjschw in forum C++ Programming
    Replies: 1
    Last Post: 12-26-2003, 01:51 PM
  3. Question...
    By TechWins in forum A Brief History of
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. float/double variable storage and precision
    By cjschw in forum C++ Programming
    Replies: 4
    Last Post: 07-28-2003, 06:23 PM
  5. Configurations give different results
    By Hubas in forum Windows Programming
    Replies: 2
    Last Post: 04-11-2003, 11:43 AM