Perl模运算符问题

Eug*_*ash 6 floating-point perl floating-accuracy

为什么第一个例子打印出错误的结果?

perl -le 'print $x = 100*1.15 % 5'
4
perl -le 'print $x = 1000*1.15 % 5'
0
Run Code Online (Sandbox Code Playgroud)

Nul*_*ion 9

这是因为浮点运算.

print $x = int(100*1.15);
Run Code Online (Sandbox Code Playgroud)

给你114.


Tas*_*kos 5

四舍五入.请记住,计算机不能完美地代表实际的小数位 - 它们是近似的.在我的计算机上,perl -le 'print $x = (100*1.15)-115'给出结果-1.4210854715202e-14,这意味着100*1.15差不多,但不完全是115.