1. 背景
实现监控两个 UIO 中断时间间隔功能时,由于无法确定两个中断发生的先后顺序,因此需要对两个中断发生时间的差值执行求绝对值运算。好在 math 包提供了对应的功能。
2. 求绝对值
Abs(var)func Abs(x float64) float64
3. 使用方法
import "math"
math.Abs(v)
4. 例程
package main
import "fmt"
import "math"
func main() {
var a int32 = -128
fmt.Printf("abs(a) = %f\n", math.Abs(float64(a))
}
执行结果:
s(a) = 128.0000005. 其他函数
math 库中包含很多常用函数,比如:
向上取整:Ceil(x float64)
向下取整:Floor(x float64)
x 的 y 次方:Pow(x, y float64)
开平方:Sqrt(x float64)
三角函数:Sin(x float64)、Cos(x float64)等。