Why does Python return 0 for simple division calcu

2019-01-01 06:10发布

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?

标签: python
3条回答
素衣白纱
2楼-- · 2019-01-01 06:16

This is a problem of integer truncation (i.e., any fractional parts of a number are discarded). So:

25 / 100 gives 0

However, as long as at least one of the operands in the division is a float, you'll get a float result:

 25 / 100.0 or 25.0 / 100  or 25.0 / 100.0 all give 0.25

查看更多
深知你不懂我心
3楼-- · 2019-01-01 06:20

25/100 is an integer calculation which rounds (by truncation) to 0.

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-01 06:21

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.

查看更多
登录 后发表回答