我发现了两种在 Python 中发言的方法:
3.1415 // 1
和
import math
math.floor(3.1415)
第一种方法的问题是它返回一个浮点数(即3.0
)。第二种方法感觉笨拙且太长。
是否有其他解决方案可以在 Python 中发言?
我发现了两种在 Python 中发言的方法:
3.1415 // 1
和
import math
math.floor(3.1415)
第一种方法的问题是它返回一个浮点数(即3.0
)。第二种方法感觉笨拙且太长。
是否有其他解决方案可以在 Python 中发言?
只要您的数字是正数,您就可以简单地转换为int
向下舍入到下一个整数:
>>> int(3.1415)
3
但是,对于负整数,这将四舍五入。
您可以在 float 上调用 int() 以投射到较低的 int (显然不是地板,但更优雅)
int(3.745) #3
或者在地板结果上调用 int。
from math import floor
f1 = 3.1415
f2 = 3.7415
print floor(f1) # 3.0
print int(floor(f1)) # 3
print int(f1) # 3
print int(f2) # 3 (some people may expect 4 here)
print int(floor(f2)) # 3
第二种方法是要走的路,但有一种方法可以缩短它。
from math import floor
floor(3.1415)
请注意,使用负数并转换为 int 并不是一回事。如果您真的希望将楼层作为整数,则应在调用 math.floor() 后转换为 int。
>>> int(-0.5)
0
>>> math.floor(-0.5)
-1.0
>>> int(math.floor(-0.5))
-1
如果int
你不想要float
int(3.1415 // 1)
from math import floor
def ff(num, step=0):
if not step:
return floor(num)
if step < 0:
mplr = 10 ** (step * -1)
return floor(num / mplr) * mplr
ncnt = step
if 1 > step > 0:
ndec, ncnt = .0101, 1
while ndec > step:
ndec *= .1
ncnt += 1
mplr = 10 ** ncnt
return round(floor(num * mplr) / mplr, ncnt)
您可以使用正数/负数和浮点数 .1、.01、.001...