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?
Regards
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?
Regards
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:
Code:int a = 4, b = 3; double ans; ans = (double) a / (double) b; //ans = 1.3333...
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:
This will yield n = 2 (rounded up from 1.66..) instead of the usual 1.Code:#include <math.h> int a = 5, b = 3, n = (int)round((double)a/b);
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
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.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}