what function should I use to truncate a real number into an integer? ( find the largest integer that does not exceed that real number)
I used to use int(x) (typecasting) but today I found a problem ( And I found a way to solve it but I don't know why it works).
For example:
1 2
double k=1.17;
cout<<int(k*100);
would output 116.
Now it's my way to fix it:
1 2 3
double k=1.17;
k*=100;
cout<<int(k);
It would output 117 as I expected.
Can anyone explain it to me? Does this work all the time?
First of all, when you say 1.17, the compiler doesn't actually store 1.17 in the variable. It stores a different number that's very close to 1.17, but that's just an approximation using double's limited precision.
When you do k*100, the intermediate result goes in a special purpose location inside the CPU that can hold floating point numbers with much more precision than a double. The result of the multiplication appears to have been 116.??? (suggesting that the approximation was <1.17). I'm willing to bet there were a few nines in the decimal part. Let's say 116.999.
When you did k*=100, however, you forced the compiler to generate code that would get this intermediate result and commit it to memory (or, at least, to convert it to double's precision to maintain semantics). The process of converting the value to a double involves rounding, so the CPU rounded 116.999 to 117.???. This is the part that's uncertain, because it could just as well have rounded it to 116.9999. The result doesn't need to be an integer.
Thanks for all the help :D.
Also if I want to round:
1 2
double k=4.5;
cout<<int(k+0.5);
usually works.
But if inside, k is actually 4.49999 and k+0.5 somehow becomes 4.99999, the rounding would fail, right?
( It actually rounds exactly for 4.5 (it outputs 5) but does it work for all other .5? )
So, how do we truncate (and round) exactly? . //Plz answer this question :D
Use the math functions floor() & ceil():-
http://www.cplusplus.com/reference/clibrary/cmath/floor/
http://www.cplusplus.com/reference/clibrary/cmath/ceil/
Halves can be represented exactly by floating point numbers, so ???.5 should give either an exact fractional value or a closest integer, depending on how big the ??? part is. For example, you can't represent exactly (10100+0.5) in a single number because that's just too many significant digits, but 10000.5 is just fine.
int(x+0.5) is a suitable rounding method for positive values of x. floor(x+0.5) will do pretty much the same thing, though it might be slightly faster.