在Python中对'int'进行类型转换会产生错误的结果 [英] Typecasting to 'int' in Python generating wrong result

查看:372
本文介绍了在Python中对'int'进行类型转换会产生错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆