🐸

数学大师

Python 基础python-architect-13-math-wizard
奖励: 80 XP
|

数学大师喜欢精确。他不喜欢“半瓶药水”或者“半个架子”。

有时你需要把数字向下取整(Floor/地板),有时需要向上取整(Ceil/天花板)。

地板与天花板

想象一个房间。地板在下面,天花板在上面。

  • math.floor(3.9) -> 3 (向下取整,像地板)
  • math.ceil(3.1) -> 4 (向上取整,像天花板)
import math

# Floor: 所谓的“地板”,就是去掉小数部分
print(math.floor(5.99)) # 5

# Ceil: 所谓的“天花板”,就是进位到下一个整数
print(math.ceil(5.01))  # 6
1
药水产量 (Floor)

我们目前有可以制作 29 / 3 = 9.66 瓶药水的材料。因为我们不能制作 0.66 瓶药水,所以需要向下取整。请使用 math.floor()

2
所需货架 (Ceil)

如果我们有 9 瓶药水,每个架子放 4 瓶,需要 2.25 个架子。我们需要向上取整以确保空间足够(即 3 个架子)。请对 max_potions / potions_per_shelf 使用 math.ceil()

为什么不用 round()?因为 round(3.5) 是 4,但 round(3.4) 是 3。在工程中,有时你需要强制指定取整的方向!

参考答案
点击展开
参考答案:
import math

# 第一步:Floor (向下取整)
potions = 29 / 3
print("Potions we can make: " + str(math.floor(potions))) # 9

# 第二步:Ceil (向上取整)
shelves_needed = 9 / 4
print("Shelves needed: " + str(math.ceil(shelves_needed))) # 3
高级技巧
想更进一步?点击展开

F. 精度至关重要

  • 在银行应用中,取整错误意味着金钱损失。
  • 在导航应用中,取整错误意味着撞墙。
  • floorceil 让你能够精准控制误差的方向。
Loading...
终端输出
Terminal
Ready to run...