Python 3.x LeetCode 69-为什么int(2.0)等于1?
我的代码如下:Python 3.x LeetCode 69-为什么int(2.0)等于1?,python-3.x,int,Python 3.x,Int,我的代码如下: 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
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)
这是基于这样的想法
当测试用例为4
时,它将输出2
,但它会返回1
我检查res
的值,它是2.0
那么这里有什么问题呢?如果你打印(repr(res))
你会看到res=1.99999999998
的int
确实是1
如果适合您的用例,您可以返回ruound(res)
(有)
如果您只对这篇wikipedia文章感兴趣,您可能会感兴趣。请省去不必要的
解决方案
类,它不是重现您的问题所必需的。你应该总是创建一个,但是无论如何,res的实际值不是2.0,(浮点数学是不精确的)它在它下面一点,我得到了类似于(1.99999999998)的东西,所以int
会给你1
注意,如果你要用math
模块来解决这个问题,您还可以使用math.sqrt
您需要无限精度的e
、ln
和pow
操作来获得不可能实现的精确2.0输出。您将始终得到结果的近似值thx!这对我理解python
中的int
有很大帮助。