简体   繁体   English

Python-除法仅在将浮点数用于除数时有效

[英]Python - Divide only worked when used floating point for divisor

Why is it that my code only worked when I turned the divisor into a float? 为什么我的代码仅在将除数转换为浮点数时才起作用?

a = 50/1000.0*100

When I did the below, it returned a 0. 当我执行以下操作时,它返回0。

a = 50/1000*100

50/1000 is 0 in python 2.x because division of integers assumes you want integer results. 在python 2.x中50/1000为0,因为整数除法假设您需要整数结果。 If you convert either the numerator or denominator to a float you will get the correct behavior. 如果将分子或分母转换为浮点数,则将获得正确的行为。 Alternatively you can use 或者,您可以使用

from __future__ import division

to get the python 3.x semantics. 获取python 3.x语义。

When both operands are integers in Python 2, a/b is the same as a//b , meaning you get integer division. 当两个操作数都是Python 2中的整数时, a/ba//b相同,这意味着您将获得整数除法。 50 / 1000 is 0 in that case (with a remainder of 50, as you can see from the return value of divmod(50, 1000) ). 在这种情况下, 50 / 1000为0(从divmod(50, 1000)的返回值可以看到,余数为50)。

if you use python 2.X above result came's if use python 3.x result is 如果您使用python 2.x以上结果是如果使用python 3.x结果是

Python 3.4.3 (default, Jul 28 2015, 18:24:59) 
[GCC 4.8.4] on linux
>>> a = 50/1000*100
>>> a
5.0
>>> a = 50/1000.0*100
>>> a
5.0
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM