2012-01-04 81 views
1

可能重复:
PHP unexpected result of float to int type cast
int((0.1+0.7)*10) = 7 in several languages. How to prevent this?增加分数数量产生不同的结果在PHP

有人可以解释我这个???

<?php 
echo (int) ((0.1 + 0.7)*10);//displays an output: `7` 
?> 

我期待看到8但我得到了7 - 请解释这种行为。

这是来自PHP的特殊功能吗?或者我不明白PHP的整数类型?

谢谢。

+0

为什么选择倒票?你介意解释吗? – 2012-01-04 11:03:59

+0

在几种语言中可能有[int((0.1 + 0.7)* 10)= 7的重复。如何防止这个?](http://stackoverflow.com/questions/6439140/int0-10-710-7-in-several-languages-how-to-prevent-this)也许[计算机如何做浮点运算?](http://stackoverflow.com/questions/6033184/how-computer-does-floating-point-arithmetic) – 2012-01-04 11:04:11

+0

有内部演示是不同的。您可能有兴趣阅读PHP手册[page](http://php.net/manual/en/language.types.float.php) – 2012-01-04 11:04:48

回答

0

这个问题在php manual

此外,有理数是在基体10精确表示作为 浮点数,如0.1或0.7,不具有 精确表示如在碱浮点数2,这是内部使用的 ,不管尾数的大小。因此,他们 不能被转换成其内部的二进制对应,没有一个精度的小损失。这可能导致混乱的结果: 例如,地板((0.1 + 0.7)* 10)通常会返回7代替 预期8,由于内部表示将会像 7.9999999999999991118 ....

相关问题