doujiao9574 2015-01-05 14:22
浏览 351
已采纳

PHP奇怪的浮点不精确

if I try to print

echo ((0.1 + 0.7) * 10);

output (http://codepad.org/m3mNNO77)

8

but if I try to print

echo (int)((0.1 + 0.7) * 10);

output (http://codepad.org/8OTCnlVG)

7

why two different results ?

  • 写回答

2条回答 默认 最新

  • dqf42223 2015-01-05 14:24
    关注

    If you perform the echo without the (int) cast, it resulits in:

    echo ((0.1 + 0.7) * 10);
    8
    

    So what happens is that the floating point actually represents it as 7.99999....

    When you perform an (int) cast, the default behavior is to take the integral part, so that's 7. Although it is extremely close to 8, it is not the behavior of a cast to round off.

    The errors are due to the fact that floating point numbers are represented with a binary radix. Representing 0.8 correctly is thus impossible. Floating points round off the answers, and hope it doesn't bother that much. When you represent the floating point like 0.8, the result is 0.80000...

    Proof of concept using the PHP interactive shell (php -a):

    $ php -a
    Interactive mode enabled
    
    php > echo number_format(((0.1 + 0.7) * 10),20)."
    ";
    7.99999999999999911182
    php > echo number_format(0.8,20);
    0.80000000000000004441
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类