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
有很大帮助。