ceili
2026/4/15大约 2 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — ceili
ceili
定义
ceili() 用来将一个数向上取整,并返回整数类型(int)——简单说,就是"只要有零头,就往上进一位"。
想象你在网上买了一箱苹果,商家说每箱最多装 6 个。如果你买了 13 个苹果,就需要 13 / 6 = 2.16... 箱,但实际上你得用 3 箱才能装完——因为零头也得单独占一箱。ceili(2.16) 返回 3,就是这个道理。
ceili 和 ceilf 功能类似,区别在于 ceili 返回的是整数(int),而 ceilf 返回的是浮点数(float)。在游戏开发中,向上取整常用于计算需要的格子数、页数、资源堆叠数等"零头也得上进"的场景。
函数签名
C#
public static int CeilToInt(float x)
// 或
public static float Ceil(float x) // 返回 float,需手动转为 intGDScript
func ceili(x: float) -> int参数说明
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
x | float | 是 | 要向上取整的浮点数 |
返回值
int —— 大于或等于 x 的最小整数。例如 ceili(2.1) 返回 3,ceili(-1.5) 返回 -1。
代码示例
C#
// 基本用法
int a = Mathf.CeilToInt(2.1f); // 3
int b = Mathf.CeilToInt(2.9f); // 3
int c = Mathf.CeilToInt(-1.5f); // -1(向上取整,-1 比 -1.5 大)
int d = Mathf.CeilToInt(5.0f); // 5(已经是整数,不变)
// 实际使用:计算装下所有物品需要的箱子数
float totalItems = 13.0f;
float itemsPerBox = 6.0f;
int boxesNeeded = Mathf.CeilToInt(totalItems / itemsPerBox); // 3
GD.Print($"需要 {boxesNeeded} 个箱子");
// 计算分页总页数
float totalRecords = 47.0f;
float recordsPerPage = 10.0f;
int totalPages = Mathf.CeilToInt(totalRecords / recordsPerPage); // 5GDScript
# 基本用法
var a = ceili(2.1) # 3
var b = ceili(2.9) # 3
var c = ceili(-1.5) # -1(向上取整,-1 比 -1.5 大)
var d = ceili(5.0) # 5(已经是整数,不变)
# 实际使用:计算装下所有物品需要的箱子数
var total_items = 13.0
var items_per_box = 6.0
var boxes_needed = ceili(total_items / items_per_box) # 3
print("需要 %d 个箱子" % boxes_needed)
# 计算分页总页数
var total_records = 47.0
var records_per_page = 10.0
var total_pages = ceili(total_records / records_per_page) # 5注意事项
ceili返回的是 int 类型,而ceilf返回的是 float 类型。如果你需要整数结果,优先使用ceili,省去了手动类型转换的麻烦。- 向上取整对于负数的表现可能不符合直觉:
ceili(-1.5)返回-1,而不是-2。因为"向上"指的是数值更大的方向(-1 > -1.5)。 - 如果传入的值本身就是整数(如
5.0),函数直接返回该整数值,不会改变。
