go语言中math.Abs和math.Floor均只接受float64参数并返回float64,整数需显式转换;Abs返回绝对值,Floor返回向下取整(朝负无穷),如math.Floor(-2.1)得-3.0。

Go语言中计算绝对值和向下取整,直接使用标准库 math 包里的 Abs 和 Floor 函数即可,但要注意参数类型和返回值类型。
math.Abs:计算绝对值
math.Abs 接收 float64 类型参数,返回 float64 类型的绝对值。它不支持整数类型(如 int)直接传入,需先转换。
- 对浮点数直接使用:
math.Abs(-3.14)→3.14 - 对整数需显式转为
float64:math.Abs(float64(-42))→42.0 - 注意:没有
math.AbsInt,也不推荐自己封装带泛型的 abs(Go 1.21+ 可用泛型,但标准库仍只提供float64版本)
math.Floor:向下取整(朝负无穷方向)
math.Floor 同样只接受 float64,返回小于或等于原值的最大整数(仍是 float64 类型),不是 int。
-
math.Floor(3.9)→3.0 -
math.Floor(-2.1)→-3.0(不是 -2!这是关键区别) - 若要转成整数,需再强制类型转换:
int(math.Floor(5.7))→5
常见组合用法示例
比如处理用户输入的浮点坐标,需取整到左下格子索引(即 floor x 和 y),再取其到原点的曼哈顿距离绝对值:
立即学习“go语言免费学习笔记(深入)”;
x, y := -2.8, 4.3 gridX := int(math.Floor(x)) // -3 gridY := int(math.Floor(y)) // 4 dist := int(math.Abs(float64(gridX))) + int(math.Abs(float64(gridY))) // 3 + 4 = 7
基本上就这些。记住核心两点:函数只认 float64,结果也返回 float64;整数运算务必手动转换,别依赖隐式类型推导。