Loss of Precision Question.

This is a discussion on Loss of Precision Question. within the C Programming forums, part of the General Programming Boards category; Hey, Im having a bit of a problem printing this data. I am trying to divide two integers and print ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    60

    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:

    Code:
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,484
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    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:
    Code:
    (float)sum / 2
    or better still make the constant a floating point value:
    Code:
    sum / 2.0
    Also, you said you wanted the output to look like b = 5.21%
    Code:
    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, 12:51 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    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

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