【问题标题】:different result 22/7 on python 2.7.12 and 3.6 [duplicate]python 2.7.12和3.6上22/7的不同结果[重复]
【发布时间】:2017-11-15 07:28:23
【问题描述】:

如何使 python 2.7 上的输出 22//7 变为 3.14159 ?我尝试使用 float(22/7) 但它只给我 3.0。我尝试使用Decimal,但它只给我3,使用round(x, 6) 只给3.0,就像float

【问题讨论】:

  • 试试float(22.0/7)
  • float(22)/7。一个数字必须是浮点类型。 float(22/7) 失败,因为在将结果转换为浮点数之前,已经通过整数除法计算结果。
  • 只需使用 22./7,这会将结果转换为浮点数
  • from __future__ import division 然后如果您想要整数除法,请使用//
  • 我希望没有任何 python 版本会在 22/7 为您提供 3.14159 的结果,因为那是错误的。

标签: python python-3.x python-2.7


【解决方案1】:

在这里,int/int 将仅返回 int,这就是这里发生的情况 22/7 给出 3,并且您将其类型转换为给出 3.0 的 float(3) 但如果您将执行 float/int 或 int/float然后它会变成浮点数,因此您可以将它们中的任何一个转换为浮点数,如下所示。

float(22/7) 替换为float(22)/7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 2012-08-13
    • 1970-01-01
    • 2021-10-23
    • 2019-06-17
    • 2014-05-20
    • 2020-05-19
    相关资源
    最近更新 更多