我有以下php for循环
$screen = 1.3; // it can be other decimal value
for ($i = 1, $k = 0; $i <= $screen; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . '<br>';
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我想运行for循环直到1.3 - 75现在它打印我1.2 - 50.我尝试将$ i <= $屏幕更改为$ i = $屏幕,但它不起作用.
如果你阅读http://php.net/manual/en/language.types.float.php,你应该记住一个很好的说法:
测试浮点值的相等性是有问题的,因为它们在内部表示的方式
为了测试浮点值的相等性,使用了由于舍入引起的相对误差的上限.此值称为机器epsilon或单位舍入,是计算中可接受的最小差异.
根据建议,您需要做以下事情:
<?php
$screen = 1.3; // it can be other decimal value
$epsilon=0.0001;
for ($i = 1, $k = 0; $i <= $screen+$epsilon; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . "\n";
}
Run Code Online (Sandbox Code Playgroud)