耐心和持久胜过激烈和狂热。
哈喽大家好,我是陈明勇,今天分享的内容是在 Go 标准库 math 常用函数和常量。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!
math
math
标准库提供了一些 常量如 int64
类型的最大值、float64
类型的最大值等,和常用的数学计算函数。
Abs 函数
Abs(x float64) float64
:返回 x
的绝对值。
- 参数
x
的类型为 float64
- 返回值也是
float64
的类型
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Abs(-3.14)) // 3.14
}
Max 函数
Max(x, y float64) float64
:并返回 x
和 y
中值最大的那个数
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Max(1.5, 2.5)) // 2.5
}
Min 函数
Min(x, y float64) float64
:并返回 x
和 y
中值最小的那个数
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Min(1.5, 2.5)) // 1.5
}
Ceil
Ceil(x float64) float64
:返回一个大于等于 x
的最小整数值,也就是向上取整。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Ceil(1.4)) // 2
fmt.Println(math.Ceil(2)) // 2
}
Floor 函数
Ceil(x float64) float64
:返回一个小于等于 x
的最小整数值,也就是向下取整。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Floor(1.4)) // 1
fmt.Println(math.Floor(1)) // 1
}
Trunc 函数
Trunc(x float64) float64
:返回浮点数 x
的整数部分,用 Floor
函数也能实现。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Trunc(1.4)) // 1
}
Dim 函数
Dim(x, y float64) float64
:返回 x-y
与 0
中最大的值。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Dim(2.0, 1.0)) // 1
fmt.Println(math.Dim(1.0, 2.0)) // 0
}
Mod 函数
Mod(x, y float64) float64
:对 x / y
进行取余运算 x % y
。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Mod(5.0, 3.0)) // 3
fmt.Println(math.Mod(3.0, 3.0)) // 0
}
Pow 函数
Pow(x, y float64) float64
:计算 x
的 y
次幂。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Pow(2, 1)) // 2
fmt.Println(math.Pow(2, 5)) // 32
}
Sqrt 函数
Sqrt(x float64) float64
:对 x
开平方。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Sqrt(64)) // 8
fmt.Println(math.Sqrt(16)) // 4
}
Cbrt 函数
Cbrt(x float64) float64
:对 x
开立方。
示例:
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Cbrt(64)) // 4
fmt.Println(math.Cbrt(8)) // 2
}