分割两个大数字时,python 3.1.2给出了错误的输出?

时间:2011-09-26 21:23:29

标签: python python-3.x

a = 25! = 15511210043330985984000000
b = 12! = 479001600
c = 13! = 6227020800

关于分割ans =(int)(a /(b * c))          或ans =(int)((a / b)/ c)

我们得到ans = 5200299而不是5200300

3 个答案:

答案 0 :(得分:11)

在Python 3.x中/表示浮点除法,可以给出小的舍入误差。使用//进行整数除法。

ans = a // (b*c)

答案 1 :(得分:5)

尝试使用整数除法而不是浮点除法。

>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200299.999999999
>>> 15511210043330985984000000 // (479001600 * 6227020800)
5200300

答案 2 :(得分:3)

你的问题(不是使用整数算术)已经在你的地毯上被Python 3.2扫地了:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200300.0
>>> repr(15511210043330985984000000 / (479001600 * 6227020800))
'5200300.0'
>>> int(15511210043330985984000000 / (479001600 * 6227020800))
5200300

Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200299.999999999
>>> repr(15511210043330985984000000 / (479001600 * 6227020800))
'5200299.999999999'
>>> int(15511210043330985984000000 / (479001600 * 6227020800))
5200299

我很困惑:大概你使用了int()因为你意识到它正在产生float答案。你为什么不采取(显而易见的?)下一步舍入它,例如。

[3.1.3]
>>> int(round(15511210043330985984000000 / (479001600 * 6227020800)))
5200300