views:

168

answers:

2

Why does the first example print a wrong result ?

perl -le 'print $x = 100*1.15 % 5'
4
perl -le 'print $x = 1000*1.15 % 5'
0
+8  A: 

It's because of floating point arithmetic.

print $x = int(100*1.15);

Gives you 114.

NullUserException
+4  A: 

Rounding. Keep in mind that computers can't represent actual decimal places perfectly - they approximate. On my computer, perl -le 'print $x = (100*1.15)-115' gives the result -1.4210854715202e-14, which means that 100*1.15 is almost, but not quite, 115.

Tassos Bassoukos