python-3.x 在花车上坐地板

qvtsj1bj  于 2023-06-25  发布在  Python
关注(0)|答案(7)|浏览(165)

在Python中,我发现了两种获取楼层的方法:

  1. 3.1415 // 1

和/或

  1. import math
  2. math.floor(3.1415)

第一种方法的问题是它返回一个浮点数(即3.0)。第二种方法让人感觉笨拙而且太长。
在Python中是否有替代的解决方案?

ao218c7q

ao218c7q1#

只要你的数字是正数,你可以简单地转换成int来向下舍入到下一个整数:

  1. >>> int(3.1415)
  2. 3

对于负整数,这将向上舍入。

wh6knrhe

wh6knrhe2#

你可以在float上调用int()来强制转换到较低的int(不明显是地板,但更优雅)

  1. int(3.745) #3

或者调用int对地板结果。

  1. from math import floor
  2. f1 = 3.1415
  3. f2 = 3.7415
  4. print floor(f1) # 3.0
  5. print int(floor(f1)) # 3
  6. print int(f1) # 3
  7. print int(f2) # 3 (some people may expect 4 here)
  8. print int(floor(f2)) # 3

http://docs.python.org/library/functions.html#int

展开查看全部
xoefb8l8

xoefb8l83#

第二种方法是可行的,但有一种方法可以缩短它。

  1. from math import floor
  2. floor(3.1415)
yrefmtwq

yrefmtwq4#

请注意,发言权和转换为整数并不是一回事,负数。如果您真的希望地板是一个整数,那么应该在调用math.floor()之后转换为一个int。

  1. >>> int(-0.5)
  2. 0
  3. >>> math.floor(-0.5)
  4. -1.0
  5. >>> int(math.floor(-0.5))
  6. -1
ztyzrc3y

ztyzrc3y5#

如果不想要float,请将其转换为int

  1. int(3.1415 // 1)
p4tfgftt

p4tfgftt6#

  1. from math import floor
  2. def ff(num, step=0):
  3. if not step:
  4. return floor(num)
  5. if step < 0:
  6. mplr = 10 ** (step * -1)
  7. return floor(num / mplr) * mplr
  8. ncnt = step
  9. if 1 > step > 0:
  10. ndec, ncnt = .0101, 1
  11. while ndec > step:
  12. ndec *= .1
  13. ncnt += 1
  14. mplr = 10 ** ncnt
  15. return round(floor(num * mplr) / mplr, ncnt)

您可以使用正数/负数和浮点.1,.01,.001...

展开查看全部
hec6srdp

hec6srdp7#

  1. number = 1.23456
  2. leftnumber = int(str(number).split('.')[0])
  3. rightnumber = str(number ).split('.')[1]

相关问题