进行大整数计算时python3中的奇怪错误 [英] Strange error in python3 when doing big int calculation

查看:25
本文介绍了进行大整数计算时python3中的奇怪错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Python 3.5.2 中做到这一点:

I was trying to do this in Python 3.5.2:

int(204221389795918291262976/10000)

却得到了意想不到的结果:20422138979591827456

but got the unexpected result: 20422138979591827456

它在 Python 2.7.12 中运行良好,结果是:20422138979591829126L

It's working fine in Python 2.7.12, result is: 20422138979591829126L

知道为什么 Python 3 给我错误的结果吗?

Any idea why Python 3 gave me the wrong result?

推荐答案

在 python 3 中,你必须显式使用整数除法 // 否则浮点除法将适用于 2 个整数之间.

In python 3 you have to use integer division // explicitly or else float division will apply even between 2 integers.

这是 python 2 和 python 3 之间的主要变化之一

That's one of the major changes between python 2 and python 3

在您的示例中:(在 python 2 和 python 3 中都可以使用,因此向后兼容!)

In your example: (will work both in python 2 and python 3 so it's backwards compatible!)

204221389795918291262976//10000
20422138979591829126

(你甚至不需要在这里转换为 int,结果是 int 因为这两个术语都是 int)

(you don't even need to convert to int here, result is int since both terms are int)

顺便说一句,如果你想让这个 bug 与 python 2 一起工作,它也是可能的:)

BTW if you want to make this bug work with python 2 it is also possible :)

from __future__ import division

这篇关于进行大整数计算时python3中的奇怪错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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