python技巧 python2中的除法结果为0

在python2中执行除法操作如果结果小于1就会返回0

如下面的例子:

        >>>81/82
        0

如果你需要返回"正确的结果 ",有两种方法:
  • 在脚本中引入from future import division
        >>> from __future__ import division
        >>> 81/82
        0.98780487804878048

  • 将除数或者被除数转换为浮点数
        >>> 81.0/82
        0.98780487804878048
        >>> 81/82.0
        0.98780487804878048

在python3中不会出现这种问题:

如下面的例子:

    Python 3.4.5 (default, Jun  1 2017, 13:52:39) 
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 81/82
    0.9878048780487805

 

 
posted @ 2018-12-11 19:00  丁壮  阅读(5124)  评论(0编辑  收藏  举报