Go是一种静态类型、编译型语言,被广泛应用于构建高性能和可靠的后端服务和系统工具。Go语言的标准库中包含了丰富的函数和类型,其中math是一个很重要的包,提供了各种数学运算函数。
math包中定义了一些常量,如下所示:
这些常量可以在进行各种数学运算时使用。
math包中提供了各种数学运算函数,下面是一些常用的函数:
Abs函数返回x的绝对值。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Abs(-12)) // Output: 12
fmt.Println(math.Abs(3.1415)) // Output: 3.1415
fmt.Println(math.Abs(0)) // Output: 0
}
Ceil函数返回大于或等于x的最小整数。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Ceil(3.1415)) // Output: 4
fmt.Println(math.Ceil(1.5)) // Output: 2
fmt.Println(math.Ceil(-2.5)) // Output: -2
}
Floor函数返回小于或等于x的最大整数。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Floor(3.1415)) // Output: 3
fmt.Println(math.Floor(1.5)) // Output: 1
fmt.Println(math.Floor(-2.5)) // Output: -3
}
Max函数返回x和y中的最大值。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Max(3, 5)) // Output: 5
fmt.Println(math.Max(-3.5, -2.5)) // Output: -2.5
fmt.Println(math.Max(3.1415, 3.14)) // Output: 3.1415
}
Min函数返回x和y中的最小值。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Min(3, 5)) // Output: 3
fmt.Println(math.Min(-3.5, -2.5)) // Output: -3.5
fmt.Println(math.Min(3.1415, 3.14)) // Output: 3.14
}
Pow函数返回x的y次方。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Pow(2, 3)) // Output: 8
fmt.Println(math.Pow(3, 2)) // Output: 9
fmt.Println(math.Pow(1.5, 0)) // Output: 1
fmt.Println(math.Pow(1.5, -2)) // Output: 0.4444444444444444
}
Sqrt函数返回x的平方根。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Sqrt(4)) // Output: 2
fmt.Println(math.Sqrt(2)) // Output: 1.4142135623730951
fmt.Println(math.Sqrt(0.25)) // Output: 0.5
fmt.Println(math.Sqrt(0)) // Output: 0
fmt.Println(math.Sqrt(-1.0)) // Output: NaN
}
Trunc函数返回x的整数部分。
示例:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Trunc(3.1415)) // Output: 3
fmt.Println(math.Trunc(-1.5)) // Output: -1
fmt.Println(math.Trunc(2.5)) // Output: 2
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。