Thread: How to not lose precision when dividing and assigning to integer?

  1. #1
    Registered User
    Join Date
    Jun 2009

    Question How to not lose precision when dividing and assigning to integer?

    Hi all,

    I want to find a way of being able not to lose precision when I am doing a division and then putting the result to an integer. How can I do that?


  2. #2
    Just a pushpin. bernt's Avatar
    Join Date
    May 2009
    I think you are wanting to store digits after the decimal place, like 4/3 = 1.3333..., right?

    In that case, you'll have to store the result as a floating point number - integers can't represent that kind of data. Just introduce a float or double and use casts, like this:

    int a = 4, b = 3;
    double ans;
    ans = (double) a / (double) b; //ans = 1.3333...

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    You can use round(), but be careful with the casting -- you obviously need to cast the return value to an int, but you also need to cast the submitted equation to a double:
    #include <math.h>
    int a = 5, b = 3, n = (int)round((double)a/b);
    This will yield n = 2 (rounded up from 1.66..) instead of the usual 1.

    As bernt points out, integers in C do not have any decimal places, but then, that is also the definition of integer in "real life".
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Portland, OR
    If you are only representing ratios of integers, then you can just store the numerator and denominator in two variables, don't actually divide anywhere, and use the rules of fractional arithmetic.
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);

Popular pages Recent additions subscribe to a feed