freepascal - Pascal double value is not exact, how to fix this? -
i have been solving programming challenge in uva , got problem, strange. here flawed code:
program wtf; begin writeln(trunc(2.01 * 100)); readln(); end.
obviously, need 201
integer
, 200
, happens because double somehow doesn't store exact value... it's 2.01 = 2.00(9)
reasons unbeknownst me, can explain , provide solution?
edit: yet, figgured using round()
instead of trunc()
fixes this... still, why wouldn't trunc()
work?
double
stores numbers of form s*2p s , p integers. number 2.01 not of form s*2p integers s, p cannot stored in double
.
the solution here round 2.01 * 100
nearest integer instead of truncating it. although 2.01
not 2.01, little bit below. rounding nearest integer result in 201.
note if 2.00(9)
mean 2.0099999999…
repeating indefinitely, 2.00(9)
is not double
when write 2.01
. nearest double
real 2.01, , number got, 2.0099999999999997868371792719699442386627197265625
. of form s * 2p: 9052235251014696 * 2-52
Comments
Post a Comment