在Python中对'int'进行类型转换会产生错误的结果 [英] Typecasting to 'int' in Python generating wrong result
问题描述
我尝试在Python 3.3中执行以下类型转换操作
I tried performing following typecast operation in Python 3.3
int(10 ** 23/10)
int( 10**23 / 10 )
输出:10000000000000000000000
Output: 10000000000000000000000
增加一个或更多的功率
int(10 ** 24/10)
int( 10**24 / 10 )
输出:99999999999999991611392
Output: 99999999999999991611392
int(10 ** 25/10)
int( 10**25 / 10 )
输出:999999999999999983222784
Output: 999999999999999983222784
为什么会这样?虽然简单的类型转换如
Why is this happening? Although a simple typecasting like
int(10 ** 24)
int( 10**24 )
输出:1000000000000000000000000
Output: 1000000000000000000000000
不影响价值。
推荐答案
您正在使用/运算符进行浮点除法。 10 ** 24/10碰巧有一个不精确的整数表示。
You are doing floating-point division with the / operator. 10**24/10 happens to have an inexact integer representation.
如果你需要一个整数结果,除以//.
If you need an integer result, divide with //.
>>> type(10**24/10)
<class 'float'>
>>> type(10**24//10)
<class 'int'>
这篇关于在Python中对'int'进行类型转换会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!