代码之家  ›  专栏  ›  技术社区  ›  Boooooooooms

LeetCode 69-为什么int(2.0)等于1?

  •  0
  • Boooooooooms  · 技术社区  · 7 年前

    import math
    class Solution(object):
        def mySqrt(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x == 0: return 0
    
            res = pow(math.e, 0.5 * math.log(x))
            print(res)
    
            return int(res)
    

    这是基于 image

    当测试用例是 4 2 但它给了 1 回来。

    res 那就是 2.0

    那么这里有什么问题?

    1 回复  |  直到 7 年前
        1
  •  0
  •   hiro protagonist    7 年前

    如果你 print(repr(res)) 你会看到的 res = 1.9999999999999998 int 那是真的 1 .

    你可以 return ruound(res) (有 doc of round )如果这适合你的用例。

    如果你对 integer square roots 只有这篇维基百科文章可能对你有意思。

    推荐文章