为什么Python进行简单的除法计算会返回0? [英] Why does Python return 0 for simple division calculation?

查看:119
本文介绍了为什么Python进行简单的除法计算会返回0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个简单的计算会返回 0

<预><代码>>>>25/100*500

虽然这实际上计算正确?

<预><代码>>>>.25*5012.5>>>10/2*210

第一个例子有什么问题?

解决方案

在 Python 2 中,25/100 在执行整数除法时为零.因为结果小于1.

您可以通过将 from __future__ import Division 添加到您的脚本中来修复"此问题.使用 / 运算符时,这将始终执行浮点除法,并使用 // 进行整数除法.

另一种选择是使至少一个操作数成为浮点数,例如25.0/100.

在 Python 3 中,25/100 总是 0.25.

Why does this simple calculation return 0

>>> 25/100*50  
0

while this actually calculates correctly?

>>> .25*50
12.5

>>> 10/2*2  
10

What is wrong with the first example?

解决方案

In Python 2, 25/100 is zero when performing an integer divison. since the result is less than 1.

You can "fix" this by adding from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division.

Another option would be making at least one of the operands a float, e.g. 25.0/100.

In Python 3, 25/100 is always 0.25.

这篇关于为什么Python进行简单的除法计算会返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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