[英]How to do floating point computation in python?
How to do floating point computation in python ? 如何在python中进行浮点计算?
for j in range(10 , 50):
print "(10/(j+1)) is %f " % (10/(j+1))
Why is the output all 0s ? 为什么输出全为0?
j must be an integer , but I need the floating result . j必须是整数,但我需要浮动结果。
thanks 谢谢
In Python2, /
will truncate the quotient of two integers into an integer, 在Python2中, /
将截断两个整数的商成一个整数,
you can either do 你可以做
for j in range(10 , 50):
print "(10/(j+1)) is %f " % (10.0/(j+1))
or not to truncate globally, just as Python3 does 还是不像Python3一样在全球范围内截断
from __future__ import division
for j in range(10 , 50):
print "(10/(j+1)) is %f " % (10/(j+1))
try 10.0 instead of 10. python is interpreting the 10 as an integer type and the division as a result is integer division. 尝试使用10.0而不是10。python将10解释为整数类型,结果除法为整数除法。 You could also cast 10 or (j + 1) to a double type manually but 10.0 seems the easiest to me. 您也可以手动将10或(j + 1)强制转换为双精度类型,但对我来说10.0似乎最简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.